4

我有大约 10 个填充的下拉列表控件。我不想复制/粘贴和修改每个字段,而是以编程方式创建它们。这可以做到吗?

这是其中一个的样子。我想以编程方式添加 10 个下拉列表控件及其各自的 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>
4

1 回答 1

11

您始终可以动态创建控件。但是在这种情况下,如果您的所有下拉列表都不同,我不确定它是否会为您节省任何东西,因为您仍然必须为它们分配单独的 ID 和数据源。

代码可能如下所示:

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();
        }
    }
}
于 2009-04-30T03:04:29.523 回答