我的aspx文件中有5个Checkboxlist。有没有办法使用foreach循环填充每个Checkboxlist?所以我不会重复代码来填充每个复选框列表。下面是我填写复选框列表的代码
CheckBoxList1.DataSource = dataTable.dbdata(sqlRawItems, 1);
CheckBoxList1.DataTextField = "StudentName";
CheckBoxList1.DataValueField = "StudentID";
CheckBoxList1.DataBind();
答案 0 :(得分:1)
private void PopulateIt(CheckBoxList chk,string dataTextField,
string dataValueField,sqlRawItems) //I don't really know what sqlRawItems is
{
chk.DataSource = dataTable.dbdata(sqlRawItems, 1);
chk.DataTextField = dataTextField;
chk.DataValueField = dataValueField;
chk.DataBind();
}
然后你可以在任何需要的地方打电话。
PopulateIt(CheckBoxList1,"StudentName","StudentID",sqlRawItems);
PopulateIt(CheckBoxList2,"StudentName","StudentID",sqlRawItems);
PopulateIt(CheckBoxList3,"StudentName","StudentID",sqlRawItems);
PopulateIt(CheckBoxList4,"StudentName","StudentID",sqlRawItems);
PopulateIt(CheckBoxList5,"StudentName","StudentID",sqlRawItems);
我不确定ASP.Net
是如何运作的,但是在winform中你可以通过控件循环来做这样的事情
foreach (CheckBox chk in this.Controls.OfType<CheckBoxList>())
{
//Of cource assuming that all the controls will bind by same data
PopulateIt(chk ,"StudentName","StudentID",sqlRawItems);
}