protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString.Count > 0)
{
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter("select * from personalization where ponumber = '" + Request.QueryString["PO"] + "'", VisualConnect);
adapter.Fill(dt);
if (dt.Rows.Count > 0)
{
for (Int32 i = 0; i < dt.Rows.Count; i++)
{
HtmlGenericControl tr = new HtmlGenericControl("tr");
HtmlGenericControl td = new HtmlGenericControl("td");
HtmlGenericControl td1 = new HtmlGenericControl("td");
Label lbcustomename = new Label();
lbcustomename.ID = "lbline1";
lbcustomename.Text = "Recipient Name: ";
td.Controls.Add(lbcustomename);
tr.Controls.Add(td);
TextBox txtcustombox = new TextBox();
txtcustombox.ID = "txtline1";
txtcustombox.Text = dt.Rows[i]["line1"].ToString();
td1.Controls.Add(txtcustombox);
tr.Controls.Add(td1);
placeholder.Controls.Add(tr);
//Add button after last record
if (i == dt.Rows.Count - 1)
{
tr = new HtmlGenericControl("tr");
td = new HtmlGenericControl("td");
Button btnSubmit = new Button();
btnSubmit.ID = "btnSubmit";
btnSubmit.Click += btnSubmit_Click;
btnSubmit.Text = "Submit";
btnSubmit.Attributes.Add("runat", "server");
td.Controls.Add(btnSubmit);
td.Attributes.Add("Colspan", "2");
td.Attributes.Add("style", "text-align:center;");
tr.Controls.Add(td);
placeholder.Controls.Add(tr);
}
}
}
}
}
private void btnSubmit_Click(object sender, EventArgs e)
{
// do something
}
}
I have added this code to dynamically draw up fields from a database for input where the user would click the Submit button when completed. However, whenever I click the submit button, it wants to reload the page and the btnSubmit_Click event is never invoked instead. Am I missing something?
Related
I have placed MultiView in UpdatePanel and added Views dynamically, each has GridView control. I'm able to display only the View which is set at first time. I have added static button for "Next" & "Back". An error "ActiveViewIndex is being set to '0'. It must be smaller than the current number of View controls '0'. For dynamically added views, make sure they are added before or in Page_PreInit event.Parameter name: value" occurs, when I click any button including these two.
Code-behind:
protected void MultiView1_Load(object sender, EventArgs e)
{
try
{
if (DropDownList4.SelectedIndex > 0)
{
int i = 1;
SqlCommand cmd = new SqlCommand("select DISTINCT(schedule) from tender where project = '" + DropDownList1.SelectedItem.ToString() + "'", agr);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
string schedule = dr[0].ToString().Trim();
GridView Gridview1 = new GridView();
Gridview1.ID = "Gridview" + i.ToString();
Gridview1.RowDataBound +=new GridViewRowEventHandler(Gridview1_RowDataBound);
Gridview1.EnableViewState = true;
Gridview1.HeaderStyle.BackColor = System.Drawing.Color.Silver;
Gridview1.HeaderStyle.ForeColor = System.Drawing.Color.White;
Gridview1.HeaderStyle.Font.Bold = true;
Gridview1.ForeColor = System.Drawing.Color.Gray;
Gridview1.AlternatingRowStyle.BackColor = System.Drawing.Color.White;
Gridview1.GridLines = GridLines.None;
Gridview1.RowStyle.BackColor = System.Drawing.ColorTranslator.FromHtml("#EFF3FB");
Gridview1.HorizontalAlign = HorizontalAlign.Center;
Gridview1.Width = 900;
DataTable dt = new DataTable();
dt.Columns.Add("SN", typeof(string));
dt.Columns.Add("SCHEDULE", typeof(string));
dt.Columns.Add("MATERIAL", typeof(string));
dt.Columns.Add("UNIT", typeof(string));
dt.Columns.Add("PREVIOUS BOQ QTY", typeof(string));
dt.Columns.Add("CURRENT QTY", typeof(string));
int j = 1;
SqlCommand cmd1 = new SqlCommand("select material from tender where project = '" + DropDownList1.SelectedItem.ToString() + "' AND schedule = '" + schedule + "' order by schedulesubsn ", agr);
SqlDataReader dr1 = cmd1.ExecuteReader();
while (dr1.Read())
{
DataRow row = dt.NewRow();
string mat = dr1[0].ToString().Trim();
row["SN"] = j;
row["SCHEDULE"] = schedule;
row["MATERIAL"] = mat;
row["UNIT"] = Calfunc.getunit(mat);
row["PREVIOUS BOQ QTY"] = Calfunc.GetLocationBOQ(DropDownList1.SelectedItem.ToString(), DropDownList2.SelectedItem.ToString(), DropDownList3.SelectedItem.ToString(), DropDownList4.SelectedItem.ToString(), schedule, mat);
dt.Rows.Add(row);
j++;
}
dr1.Dispose();
View view = new View();
view.ID = schedule;
view.Controls.Add(Gridview1);
MultiView1.Views.Add(view);
Gridview1.DataSource = dt;
Gridview1.DataBind();
i++;
}
dr.Dispose();
MultiView1.ActiveViewIndex = i-3;
}
}
catch (Exception ex)
{
}
}
protected void Button3_Click(object sender, EventArgs e)
{
if (MultiView1.ActiveViewIndex > 0)
{
MultiView1.ActiveViewIndex = MultiView1.ActiveViewIndex - 1;
}
}
protected void Button4_Click(object sender, EventArgs e)
{
if (MultiView1.Views.Count-1 > MultiView1.ActiveViewIndex)
{
TextBox2.Text = (MultiView1.ActiveViewIndex + 1).ToString();
}
}
protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
TextBox TextBox101 = new TextBox();
TextBox101.ID = "TextBox_C_QTY";
TextBox101.Width = 70;
TextBox101.Text = (e.Row.DataItem as DataRowView).Row["CURRENT QTY"].ToString();
e.Row.Cells[5].Controls.Add(TextBox101);
}
}
aspx:
<asp:UpdatePanel ID="UpdatePanel4" runat="server">
<ContentTemplate>
<div style="overflow-x:auto;">
<asp:MultiView ID="MultiView1" runat="server" onload="MultiView1_Load">
</asp:MultiView>
</div>
</ContentTemplate>
</asp:UpdatePanel>
I've searched for the solution but didn't find any satisfactory or workable (for me).
I have a search function which looks up specific users in my OleDb database. For each user, a row in a table is created containing his name, boolean saying if he is an admin or not and a delete button. The delete button is not working as expected, it doesn't execute the method that is linked to it. My code is located in the Search_Click event which executes right after the admin clicks the search button to search for specific users.
I tried to place a pre-defined button from my code but in Page_Load instead and it works as expected. How can I get the button to work from the Search_Click as well?
Basically, after dynamically creating the LinkButtons according to the user search text and clicking the search button (Search_Click) I need to find a way to register the click event on page load event, I do not know how to do that because the linkbuttons HAVE to be created in the click event of the search button but they also have to be registered via page load.
using (OleDbDataReader reader = cmd.ExecuteReader())
{
Table table = new Table();
TableRow row = new TableRow();
TableCell cell = new TableCell();
Label label = new Label();
while (reader.Read())
{
row = new TableRow();
cell = new TableCell();
label = new Label();
label.Text = reader.GetString(0);
cell.Controls.Add(label);
cell.BorderStyle = BorderStyle.Solid;
row.Cells.Add(cell);
cell = new TableCell();
label = new Label();
label.Text = reader.GetBoolean(1).ToString();
cell.Controls.Add(label);
cell.BorderStyle = BorderStyle.Solid;
row.Cells.Add(cell);
cell = new TableCell();
LinkButton button = new LinkButton();
button.Text = "Delete";
button.ID = (string) reader["uName"];
button.CommandName = (string)reader["uName"];
button.Click += new EventHandler(DeleteUser);
cell.Controls.Add(button);
cell.BorderStyle = BorderStyle.Solid;
row.Cells.Add(cell);
table.Rows.Add(row);
}
table.Style.Add(HtmlTextWriterStyle.MarginLeft, "auto");
table.Style.Add(HtmlTextWriterStyle.MarginRight, "auto");
TableHolder.Controls.Add(table);
}
DeleteUser:
protected void DeleteUser(object sender, EventArgs e)
{
try
{
LinkButton button = (LinkButton)sender;
string path = Server.MapPath(#"App_Data/ArcadeDatabase.accdb");
using (OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + "; Persist Security Info = False;"))
{
try
{
con.Open();
}
catch(Exception ex)
{
helper.Log("OleDbError", ex.Message);
}
if(con.State == System.Data.ConnectionState.Open)
{
using (OleDbCommand cmd = new OleDbCommand("DELETE * FROM ArcadeDatabase WHERE uName ='" + button.CommandName + "';", con))
{
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
helper.Log("OleDbError", ex.Message);
}
}
}
con.Dispose();
}
path = "";
}
catch (Exception ex)
{
helper.Log("Admin", ex.Message);
}
}
The event handler for dynamic controls need to be registered during Page_Load / Page_Init events to be triggered (see this link).
So, You have to add your Delete button and its event handler in page_load or init. to find ID of the control which cause postback in Page_Init event, see this
UPDATE:
OK, i add this code to proof it can be done without problems.
To see how it works: create a new Web Form and paste the following HTML & Code-Behinds into it. Then run the app and type some name in Search TextBox (eg: John or Ali) and press Search Button to filter the results.
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
string searchName = "";
if (SearchTextBox.Text != "") //if (this.GetPostBackControlUniqueID() == Search.UniqueID) //Search button is clicked!
{
searchName = SearchTextBox.Text;
}
addTable(searchName);
}
void addTable(string searchName)
{
string[] data = new[] {
"John, false, usrJohn"
,"Alex, false, usrAlex"
,"Ali, true, usrAli"
};
//using (OleDbDataReader reader = cmd.ExecuteReader())
//{
Table table = new Table(); table.CellPadding = 10;
TableRow row;
TableCell cell;
Label label;
foreach(string dataItem in data) //while (reader.Read())
{
string[] reader = dataItem.Split(',');
if (reader[0].IndexOf(searchName, StringComparison.OrdinalIgnoreCase) < 0) continue; //search not found (in real app, you use sql where clause for this, but this is just for test)
row = new TableRow();
cell = new TableCell();
label = new Label();
label.Text = reader[0].Trim(); //reader.GetString(0);
cell.Controls.Add(label);
cell.BorderStyle = BorderStyle.Solid;
row.Cells.Add(cell);
cell = new TableCell();
label = new Label();
label.Text = reader[1].Trim(); //reader.GetBoolean(1).ToString();
cell.Controls.Add(label);
cell.BorderStyle = BorderStyle.Solid;
row.Cells.Add(cell);
cell = new TableCell();
LinkButton button = new LinkButton();
button.Text = "Delete";
string uName = reader[2].Trim();
button.ID = uName; //(string)reader["uName"];
button.CommandName = uName; //(string)reader["uName"];
button.Click += new EventHandler(DeleteUser);
cell.Controls.Add(button);
cell.BorderStyle = BorderStyle.Solid;
row.Cells.Add(cell);
table.Rows.Add(row);
}
table.Style.Add(HtmlTextWriterStyle.MarginLeft, "auto");
table.Style.Add(HtmlTextWriterStyle.MarginRight, "auto");
TableHolder.Controls.Add(table);
//} //end using OleDbDataReader reader
}
protected void Search_Click(object sender, EventArgs e)
{
//addTable(SearchTextBox.Text); //already done in Page_Load
}
protected void DeleteUser(object sender, EventArgs e)
{
LinkButton button = (LinkButton)sender;
//using (OleDbCommand cmd = new OleDbCommand("DELETE * FROM ArcadeDatabase WHERE uName ='" + button.CommandName + "';", con))
string sql = "DELETE * FROM ArcadeDatabase WHERE uName ='" + button.CommandName + "';";
//execute the sql ... (in real app)
TableHolder.Controls.Add(new LiteralControl("The sql was: " + sql));
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = DateTime.Now.ToString("HH:mm:ss");
}
} //end class
And this is the helper extension method to Get UniqueID of PostBack Control:
// ***********************************************************************
public static class MyWebPageExtensions
{
public static string GetPostBackControlUniqueID(this Page page)
{
if (!page.IsPostBack)
return string.Empty;
Control control = null;
string controlName = page.Request.Params["__EVENTTARGET"]; //this method works only for link buttons which use javascript: __doPostBack(...) and not input type=submit buttons. Note: it is also available in Request.Form collection but this doesn't require to loop over Form.
if (!String.IsNullOrEmpty(controlName))
{
control = page.FindControl(controlName);
}
else
{
// __EVENTTARGET is null, the control is a button (not javascript linkButton), we need to iterate over the form collection to find it
foreach (string id in page.Request.Form)
{
// handle ImageButton they having an additional "quasi-property" in their Id which identifies mouse x and y coordinates
if (id.EndsWith(".x") || id.EndsWith(".y"))
{
string id2 = id.Substring(0, id.Length - 2);
control = page.FindControl(id2);
}
else
{
control = page.FindControl(id);
}
if (control is IButtonControl) break;
}
}
return control == null ? String.Empty : control.UniqueID;
}
}
try
{
string constr1 = ConfigurationManager.ConnectionStrings["constring"].ConnectionString;
SqlConnection conn1 = new SqlConnection(constr1);
conn1.Open();
//passing a query to fetch the table from database,which is entered in TextBox
DataSet ds = new DataSet();
string s2 = "select neid,keyholder from tbl_controller_settings where axxesstype='2'";
SqlDataAdapter da = new SqlDataAdapter(s2, conn1);
da.Fill(ds);
DataTable dt = new DataTable();
dt = ds.Tables[0];
//creating a table dynamically
HtmlTable table = new HtmlTable();
HtmlTableRow tr = null;
HtmlTableCell tc = null;
//displaying labels for displaying column names in the table
tr = new HtmlTableRow();
for (int i = 0; i <=64; i++)
{
tc = new HtmlTableCell();
Label lbl = new Label();
if(i!=0)
lbl.Text = "Key"+" "+i.ToString();
lbl.ID = "lbl" +" "+i.ToString();
lbl.Style.Add("writing-mode", "rt-tb");
lbl.Style.Add("filter", "flipv");
tc.Height = "50px";
tc.Width = "150px";
tc.Controls.Add(lbl);
tr.Controls.Add(tc);
table.Controls.Add(tr);
}
//creating textboxes for displaying records information
for (int j = 0; j < dt.Rows.Count; j++)
{
tr = new HtmlTableRow();
tc = new HtmlTableCell();
Label ksid = new Label();
ksid.ID = "ksid"+j;
ksid.Text = dt.Rows[j][0].ToString();
tc.Controls.Add(ksid);
tr.Controls.Add(tc);
for (int k = 1; k <= 64;k++ )
{
tc = new HtmlTableCell();
CheckBox chk = new CheckBox();
chk.ID = "txt" + j + k;
chk.CheckedChanged += new EventHandler(CheckBox_CheckedChanged);
if (k <= Convert.ToInt32(dt.Rows[j][1]))
chk.Enabled = true;
else
chk.Enabled = false;
tc.Controls.Add(chk);
tr.Controls.Add(tc);
}
table.Controls.Add(tr);
}
pnlkeys.Controls.Add(table);
pnlkeys.Visible = true;
//}
}
catch (Exception ex)
{
throw;
}
Hello
In the Above code i have created the check box and a label button dynamically,in this 64 iteration i will be having the 64 check box.i want to get the value has when a check box is checked it should be 1 and when it is not checked it should be 0 to store in 64 columns ..please help me
try add the method in the same class file :
public static void CheckBox_CheckedChanged(object sender, EventArgs e) {
}
If you want help on how to generate the "1" when checked, please specify first where that value is to be stored.
You do not need OnCheckedChanged if you want to store their values altogether.
You can access your CheckBox's value in PostBack on Request.Form with their ID
if(Request.Form["txt11"]==null)
{
//checkbox is not checked
}
if(Request.Form["txt11"]=="on")
{
//checkbox is checked
}
You need to write this code in a loop to get all your CheckBoxes
I am creating a dynamically repeater during the creation of this repeater I create some dropdownlists with autopostback = true, and add the handler selectindexchanged. I wonder how to keep bind the repeater inside (! IsNotPostBack) without losing the repeater information. In summary if I keep bind the repeater in notpostback, when I change the dropdownlist the repeater is not rendered.
Well confused? I will post part of the code:
Default.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindRepeater2();
}
}
private void BindRepeater2()
{
Repeater rContainer = null;
HtmlGenericControl div = new HtmlGenericControl("div");
HtmlGenericControl table = new HtmlGenericControl("table");
div.Attributes.Add("class", "CompApp_TableScroll");
table.Attributes.Add("class", "CompApp_DataTable");
table.Attributes.Add("width", "100%");
try
{
DataTable dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Address", typeof(string));
dt.Columns.Add("DropDown", typeof(string));
dt.Rows.Add(25, "Rk", "Gurgaon");
dt.Rows.Add(50, "Sachin", "Noida");
dt.Rows.Add(10, "Nitin", "Noida");
dt.Rows.Add(21, "Aditya", "Meerut");
DataSet ds = new DataSet();
ds.Tables.Add(dt);
if (dt.Rows.Count > 0)
{
rContainer = new Repeater();
rContainer.DataSource = dt;
rContainer.DataBind();
foreach (DataTable dtCluster in ds.Tables)
{
rContainer = new Repeater();
rContainer.ItemTemplate = new RepeaterTemplate2(ListItemType.Item);
rContainer.HeaderTemplate = new RepeaterTemplate2(ListItemType.Header);
rContainer.FooterTemplate = new RepeaterTemplate2(ListItemType.Footer);
rContainer.DataSource = dtCluster;
table.Controls.Add(rContainer);
}
div.Controls.Add(table);
}
div1.Controls.Add(div);
rContainer.ItemDataBound += rContainer_ItemDataBound;
rContainer.ID = "rpt1";
rContainer.DataBind();
}
catch (Exception ex)
{
throw ex;
}
}
void rContainer_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DropDownList ddl = new DropDownList();
ddl = (DropDownList)e.Item.FindControl("ddl");
ddl.AutoPostBack = true;
ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
}
}
private void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl2 = new DropDownList();
ddl2 = (DropDownList)sender;
Response.Write(ddl2.SelectedValue);
}
RepeaterTemplate2.cs
public class RepeaterTemplate2 : System.Web.UI.ITemplate
{
ListItemType vTemplateItemType = ListItemType.Separator;
public RepeaterTemplate2(ListItemType pListItemType)
{
vTemplateItemType = pListItemType;
}
public void InstantiateIn(System.Web.UI.Control container)
{
Literal lc = new Literal();
HtmlGenericControl tr = new HtmlGenericControl("tr");
HtmlGenericControl td = new HtmlGenericControl("td");
switch (vTemplateItemType)
{
case ListItemType.Header:
td.InnerHtml = "<u>EmpID</u>";
tr.Controls.Add(td);
td = new HtmlGenericControl("td");
td.InnerHtml = "<u>Name</u>";
tr.Controls.Add(td);
td = new HtmlGenericControl("td");
td.InnerHtml = "<u>Address</u>";
tr.Controls.Add(td);
td = new HtmlGenericControl("td");
td.InnerHtml = "<u>DropdDown</u>";
tr.Controls.Add(td);
break;
case ListItemType.Footer:
break;
case ListItemType.Item:
; break;
}
tr.DataBinding += new EventHandler(lc_DataBinding);
container.Controls.Add(tr);
}
private void lc_DataBinding(object sender, EventArgs e)
{
HtmlGenericControl tr = (HtmlGenericControl)sender;
RepeaterItem vContainer = (RepeaterItem)tr.NamingContainer;
DataRowView row = (DataRowView)vContainer.DataItem;
if (row != null)
{
for (int i = 0; i < row.DataView.Table.Columns.Count; i++)
{
HtmlGenericControl td = new HtmlGenericControl("td");
if (i == 3)
{
DropDownList ddl = new DropDownList();
ddl.ID = "ddl";
ddl.Items.Add(new ListItem("valor 1", "1"));
ddl.Items.Add(new ListItem("valor 2", "2"));
td.Controls.Add(ddl);
}
else
{
td.InnerHtml = row[i].ToString();
}
tr.Controls.Add(td);
}
}
}
}
I am using the following lines of code for a button in C# :
void reserve_click(object sender, EventArgs e)
{
string req = ((Button)sender).ID;
}
protected void Button2_Click(object sender, EventArgs e)
{
issuedBooks.Visible = false;
search.Visible = true;
string text = TextBox1.Text;
string selectCommand = "SELECT id, title, author FROM book WHERE title LIKE '%" + text + "%' OR author LIKE '%" + text + "%'";
string conString = WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlDataAdapter dad = new SqlDataAdapter(selectCommand, conString);
DataTable dtblCategories = new DataTable();
dad.Fill(dtblCategories);
DataView view = new DataView(dtblCategories);
foreach (DataRowView row in view)
{
TableRow newrow = new TableRow();
TableCell newcell1 = new TableCell();
TableCell newcell2 = new TableCell();
TableCell newcell3 = new TableCell();
newcell1.Text = row["title"].ToString();
newrow.Cells.Add(newcell1);
newcell2.Text = row["author"].ToString();
newrow.Cells.Add(newcell2);
string book_id = row["id"].ToString();
Button btn = new Button();
btn.ID = "Button_1" + book_id;
btn.Text = "Reserve";
btn.Click += new EventHandler(reserve_click);
newcell3.Controls.Add(btn);
newrow.Cells.Add(newcell3);
search.Rows.Add(newrow);
}
I am using the above code in a dynamically added button in a table cell. But the above EventHandler is not working or getting fired. I am using asp.net and C#for the first time. Can someone help me out ? Thanks.
here is the answer.Try it
Page_Load()
{
Button b = new Button();
b.ID = topic.Topic_Id + "_1"; // topic_Id is my unique ID for each topic on the blog
b.Text = "Edit";
b.ToolTip = "Edit";
b.CommandArgument = b.ID; //passing this to event handler
b.Command += new CommandEventHandler(b_Command); //handler
}
void b_Command(object sender, CommandEventArgs e)
{
System.Windows.Forms.MessageBox.Show(e.CommandArgument.ToString());
}