1

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:

Compiler Error Message: CS0103: The name 'mySelect' does not exist in the current context.

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"?

ChrisLiu
  • 11
  • 4
  • regarding your table, why not just use html to create your table, and if you're using it to display data, databind a repeater control? regarding the select, why not just databind that as well, or use asp:ListItem in the html code to add items to the dropdown? no need to dynamically add items on page load unless you're using ajax to refresh the list at a later time. also, the reason you're getting an error is because the id of your dropdown list is "a_content_type" when the codebehind expects "mySelect" – Chris Brickhouse Aug 15 '13 at 15:09

1 Answers1

0

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.

ChrisLiu
  • 11
  • 4
  • you realize, of course, that you create, set and then use a new `clientID` property of javascript global `window` object? See my update. – Igor Aug 16 '13 at 02:26