Based on certain condition, I have created a few checkboxes, dropdownlists and textboxes dynamically in the Page_Init().In the same page, I have a Submit button that is created during the design time (in the aspx page). Following is the part of the code. The textbox’s visibility is controlled by the checkbox.
Now I have two problems need to solve: (1) ddl.selectedIndex is always initialized to 0 not -1. But in the event handler Sumbit_Click(), the ddl.selectedIndex is 0 even I didn’t select any item. (2) Also even the checkbox is checked, during the postback, the textbox doesn’t show. Is there any way to fix it?
DropDownList ddl = new DropDownList();
ddl.ID = "ddl" + id;
ddl.DataSource = subCallReasonEntityList;
ddl.DataTextField = "myText";
ddl.DataValueField = "id";
ddl.DataBind();
ddl.SelectedIndex = -1;
cell.Controls.Add(ddl);
CheckBox cb = new CheckBox();
cb.ID = "cb" + id;
cb.ClientIDMode = ClientIDMode.Static;
cell.Controls.Add(cb);
cell.Controls.Add(new LiteralControl("<br />"));
TextBox tb = new TextBox();
tb.ID = "txt" + id;
tb.ClientIDMode = ClientIDMode.Static;
tb.Attributes.Add("style", "display:none");
cb.Attributes.Add("onclick", "return cbOtherClicked('" + cb.ClientID + "', '" + tb.ClientID + "')");
cell.Controls.Add(tb);
function cbOtherClicked(control1, control2) {
var cbOther = document.getElementById(control1);
var txtOther = document.getElementById(control2);
if (cbOther.checked) {
txtOther.style.display = "block";
}
else {
txtOther.style.display = "none";
}
}