I have to generate multiple dropdownlists on clie开发者_StackOverflowntclick. That is new dropdownlists on every client click. I placed a button and wrote code on click event.
protected void addReq1_Click(object sender, ImageClickEventArgs e)
{
DropDownList oDdl = new DropDownList();
oDdl.ID = "ddlReq" + (++i).ToString();
oDdl.DataSourceID = "DSUsers";
oDdl.DataTextField = "UName";
oDdl.DataValueField = "UName";
HtmlTableCell tc0 = new HtmlTableCell();
HtmlTableCell tc1 = new HtmlTableCell();
HtmlTableCell tc2 = new HtmlTableCell();
HtmlTableCell tc3 = new HtmlTableCell();
tc2.Controls.Add(oDdl);
HtmlTableRow tr = new HtmlTableRow();
tr.Cells.Add(tc0);
tr.Cells.Add(tc1);
tr.Cells.Add(tc2);
tr.Cells.Add(tc3);
search2.Rows.Add(tr);
}
Here "DSUsers" is SqlDataSource.
"i" is static variable.
"serarch2" is html table with runat server tag
The problem is only one control is getting rendred, after that on every additional click same DropDownList is getting replaced. No new DropDownList is added to the page.
Thank You.
When you dynamically add any controls to your page, they are lost on the next postback. In order for this to work, you will need to test i in your PreInit or Init event and create the correct number of rows there.
for (int x = 0 to i) {
DropDownList oDdl = new DropDownList();
oDdl.ID = "ddlReq" + (++x).ToString();
oDdl.DataSourceID = "DSUsers";
oDdl.DataTextField = "UName";
oDdl.DataValueField = "UName";
HtmlTableCell tc0 = new HtmlTableCell();
HtmlTableCell tc1 = new HtmlTableCell();
HtmlTableCell tc2 = new HtmlTableCell();
HtmlTableCell tc3 = new HtmlTableCell();
tc2.Controls.Add(oDdl);
HtmlTableRow tr = new HtmlTableRow();
tr.Cells.Add(tc0);
tr.Cells.Add(tc1);
tr.Cells.Add(tc2);
tr.Cells.Add(tc3);
search2.Rows.Add(tr);
}
Obligatory link to the ASP.NET page lifecycle.
精彩评论