Thursday, September 25, 2008

DataSet / DataTable Primary Key and using DataRow.Find

It's quick and easy to find items in a DataTable through setting the primary key. This method can be used to easily populate a CheckBoxList

DataSet ds = //populate dataset
if(ds != null && ds.Tables.Count > 0)
{
  GroupCBL.DataSource = ds;
  GroupCBL.DataTextField="textField";
  GroupCBL.DataBind();

  DataColumn[] dc = new DataColumn[1];
  dc[0] = ds.Tables[0].Columns["key"];
  ds.Tables[0].PrimaryKey = dc;

  foreach(ListItem item in GroupCBL.Items)
  {
    DataRow row = ds.Tables[0].Rows.Find(item.Value);
    item.Selected = Convert.ToBoolean(row["selected"]);
  }
}

No comments: