【问题标题】:ASP.Net: drop down list and data source created dynamicallyASP.Net:动态创建的下拉列表和数据源
【发布时间】:2009-04-30 02:39:39
【问题描述】:

我有大约 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>

【问题讨论】:

    标签: asp.net drop-down-menu sqldatasource dynamic-controls


    【解决方案1】:

    您始终可以动态创建控件。但是在这种情况下,如果您的所有下拉列表都不同,我不确定它是否会为您节省任何东西,因为您仍然必须为它们分配单独的 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();
            }
        }
    }
    

    【讨论】:

    • 创建下拉列表控件时缺少某些内容。您必须添加一些属性,例如 question(DataSourceid="ddlDAGender", DataTextField="Gender", DataValueField="GenderID")
    猜你喜欢
    • 2015-11-06
    • 1970-01-01
    • 2021-05-18
    • 1970-01-01
    • 2011-10-25
    • 1970-01-01
    • 2015-01-06
    • 2011-07-31
    • 2018-07-22
    相关资源
    最近更新 更多