Reputation: 750
I have 5 Checkboxlist in my aspx file. Is there a way to populate each Checkboxlist using a foreach loop? so that I will not repeating the code to populate each checkboxlist. Below is my code to populate the checkboxlist
CheckBoxList1.DataSource = dataTable.dbdata(sqlRawItems, 1);
CheckBoxList1.DataTextField = "StudentName";
CheckBoxList1.DataValueField = "StudentID";
CheckBoxList1.DataBind();
Upvotes: 0
Views: 182
Reputation: 15613
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();
}
Then you can call it wherever you need it.
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);
I'm not sure how ASP.Net
works, but in winform you could do somthing like this for looping through your controls
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);
}
Upvotes: 1