大家好我需要将下拉列表绑定到数据库中的值。每个下拉列表都在一个面板中,我以连续的方式将其命名为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();
}
请帮忙
答案 0 :(得分: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();
}
答案 1 :(得分: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();
}