0

大家好,我需要将下拉列表绑定到数据库中的值。每个下拉列表都将在一个面板内,我以连续的方式将其命名为 ddlxx1、ddlxx2、ddlxx3。所有这些下拉列表都将具有相同的数据源。有没有办法在循环中绑定这些控件,或者我应该每次在面板中找到控件然后绑定它?

就像是:

            for(int i=1;i<=10;i++)
            {
            ddlxx+"i".DataSource = Prod.GetValues();
            ddlxx+"i".DataTextField = "ComponentID";
            ddlxx+"i".DataValueField = "ComponentName";
            ddlxx+"i".DataBind();
            }

请帮忙

4

2 回答 2

1

如果您的下拉列表被添加到标记中,您可以简单地执行以下操作:

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
       for(int i=1;i<=10;i++)
        {
          var ddl =  FindControl("ddlxx" + i) as DropDownList;
          if (ddl != null)
          {
            BindDropDown(ddl);
          }
        }
    }
}

private void BindDropDown(DropDownDataList ddl) 
{
   ddl.DataSource = Prod.GetValues();
   ddl.DataTextField = "ComponentID";
   ddl.DataValueField = "ComponentName";
   ddl.DataBind();
}
于 2013-06-19T08:23:23.843 回答
0

尝试这个:

        for (int i = 1; i <= 10; i++)
        {
            DropDownList drp = (DropDownList)panel1.FindControl("ddlxx" + i.ToString());//panel1 is your panel which contain dropdown ddlxx1,ddlxx2,ddlxx3...
            drp.DataSource = Prod.GetComponents();
            drp.DataTextField = "ComponentID";
            drp.DataValueField = "ComponentName";
            drp.DataBind();
        }
于 2013-06-19T08:30:11.313 回答