/******************************************************************************
Q10028 - C#: Working with a CheckBoxList
Article ID: Q10028
Created Date: 5/7/2007
Last Modified: 5/7/2007
Author: Dale
Original URL: http://www.geekycodesamples.com/article.aspx?id=10028
******************************************************************************/
// How to populate a CheckBoxList from a DataTable
private void PopulateCheckboxList(CheckBoxList chkList)
{
ProdConfigSupport pcs = new ProdConfigSupport();
DataTable dt = pcs.GetProductList();
if (dt != null && dt.Rows.Count > 0)
{
chkList.DataSource = dt;
chkList.DataTextField = "ProductDescription";
chkList.DataValueField = "ProductID";
chkList.DataBind();
chkList.Visible = true;
}
else
{
chkList.Visible = false;
}
}
// How to iterate through a checkbox list. In this case we are
// capturing the ‘value’ of any Checkboxes that were selected
// and packaging them into an ArrayList
ArrayList arySelectedProducts = new ArrayList();
foreach (ListItem itm in chkBoxListProducts.Items)
{
if (itm.Selected)
{
arySelectedProducts.Add(itm.Value);
}
}
// How to programmatically ‘check’ the previously-checked selections
// of a CheckBoxList. In this case, the method
// GetPreviouslySelectedProducts() populates an ArrayList called
// arySelectedProducts that contains a list of the ProductID’s
// that should be ‘checked’
ArrayList arySelectedProducts = GetPreviouslySelectedProducts();
foreach (ListItem itm in this. chkBoxListProducts.Items)
{
if (arySelectedProducts.Contains(Convert.ToString(itm.Value)))
{
itm.Selected = true;
}
}