Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net: drop down list and data source created dynamically

I have about 10 drop down list controls that get populated. Instead of copying/pasting and modifying a few fields on each, I would like to create them programmatically. Can this be done?

Here is what one of them looks like. I would like to 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>
like image 244
dotnet-practitioner Avatar asked Dec 23 '22 11:12

dotnet-practitioner


1 Answers

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();
        }
    }
}
like image 153
womp Avatar answered Dec 25 '22 01:12

womp