如何循环所有 CheckBoxList 然后填充它们?

How to loop in all CheckBoxList then populate them?

我的 aspx 文件中有 5 个复选框列表。有没有办法使用 foreach 循环填充每个复选框列表?这样我就不会重复代码来填充每个复选框列表。下面是我填充复选框列表的代码

CheckBoxList1.DataSource = dataTable.dbdata(sqlRawItems, 1);
CheckBoxList1.DataTextField = "StudentName";
CheckBoxList1.DataValueField = "StudentID";
CheckBoxList1.DataBind();
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);        
}