Pregunta

Tengo unos 10 controles de lista desplegable que se rellenan. En lugar de copiar / pegar y modificar algunos campos en cada uno, me gustaría crearlos mediante programación. Se puede hacer esto?

Así es como se ve uno de ellos. Me gustaría agregar mediante programación 10 controles de lista desplegable y sus respectivos controles SqlDataSource.

   <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>
¿Fue útil?

Solución

Siempre puedes crear tus controles dinámicamente. Sin embargo, en este caso, si todas sus listas desplegables son diferentes, no estoy seguro de que le esté ahorrando algo, ya que aún tendrá que asignarles identificaciones individuales y fuentes de datos.

Así es como se vería el código:

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();
        }
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top