I'm a fresh of ASP.NET, I meet the problem in my work, please help.
I want to dynamically add the options into a dropdownlist in ASP page. So I write a javascript function:
<body>
<form id="form1" runat="server" style="height:100%">
</form>
<script type="text/javascript">
function addOptionToSelect(optKey, optValue) {
var select = document.getElementById('<%=mySelect.ClientID%>');
var opt = new Option(thisLabel, thisValue);
select.add(opt);
}
}
</script>
</body>
For some reasons, I have to add the dropdownlist web control in code-behind of the ASP:
protected void Page_Load(object sender, EventArgs e)
{
Table t = new Table();
form1.Controls.Add(t);
TableRow r = new TableRow();
formatTable.Rows.Add(r);
TableCell c = new TableCell();
formatRow.Cells.Add(c);
DropDownList select = new DropDownList();
select.ID = "mySelect";
select.Text = "mySelect:";
c.Controls.Add(select);
}
I will get the error:
However, if I add the dropdownlist in ASP page directly, there is no error.
<form id="form1" runat="server" style="height:100%">
<div>
<asp:DropDownList ID="a_content_type" runat="server">
</asp:DropDownList>
</div>
</form>
How should I solve the error? And What's the difference of "add asp web control in ASP page" and "add asp web control in code-behind"?
I think I find another way to solve the problem. First, I add a new function in the ASP Header:
function setClientID(id) { this.clientID = id; }
Then, add the below code to code-behind after creating dropdownlist:
Page.ClientScript.RegisterStartupScript(this.GetType(), "setClientID", "setClientID('" + mySelect.ClientID + "');", true);
Finally, user "this.ClientID" to replace the "<%=mySelect.ClientID%>". It works.