vote up 0 vote down
star

Hi

I have about 10 drop down list controls that get populated. Instead of copying / pasting and modifying few fields I would like to create them programmatically. Can this be done? Here is one of them looks like... I would like programmatically add 10 dropdownlist controls and their respective SqlDataSource controls.

   <asp:SqlDataSource ID = "ddlDAGender" runat=server
    ConnectionString="<%$ ConnectionStrings:test1ConnectionString %>" 
    SelectCommand = "select GenderID,Gender from mylookupGender"
    >
    </asp:SqlDataSource>


 <asp:Label ID="Label3" runat="server" Text="Gender"></asp:Label>

        <asp:DropDownList ID="ddlGender" runat="server" 
                DataSourceid="ddlDAGender"
                DataTextField="Gender" DataValueField="GenderID"

    >

 </asp:DropDownList>
flag
add comment

1 Answer:

vote up 2 vote down
check

You can always create your controls dynamically. In this case though, if all your drop down lists are different, I'm not sure it's saving you anything, since you'll still have to assign them individual ID's and datasources.

Here's what the code might look like:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindDropDownLists();
    }
}

protected void Page_Init(object sender, EventArgs e)
{ 

        SqlDataSource sqlDS = new SqlDataSource();
        sqlDS.ConnectionString = ConfigurationManager.ConnectionStrings[0].ToString();
        sqlDS.SelectCommand = "select GenderID,Gender from mylookupGender";
        form1.Controls.Add(sqlDS);

        DropDownList ddl = new DropDownList();
        ddl.ID = "dddlGender";
        ddl.DataSource = sqlDS;
        ddl.DataTextField = "Gender";
        ddl.DataValueField = "GenderID";
        form1.Controls.Add(ddl);

        // ... Repeat above code 9 times or put in a for loop if they're all the same...
}

private void BindDropDownLists()
{
    foreach (Control ctl in form1.Controls)
    {
        if (ctl is DropDownList)
        {
            (ctl as DropDownList).DataBind();
        }
    }
}
link|flag
Something is missing in creating Dropdownlist control. You must add some property like question(DataSourceid="ddlDAGender", DataTextField="Gender", DataValueField="GenderID") – Soul_Master Apr 30 at 3:25
add comment

Your Answer:

Get an OpenID
or

Not the answer you're looking for? Browse other questions tagged or ask your own question.