65.9K
CodeProject is changing. Read more.
Home

Databinding CheckListBoxControl with DataView

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.47/5 (9 votes)

Mar 7, 2005

viewsIcon

64161

Databinding CheckListBoxControl with DataView.

Introduction

After a long day of struggle to get DevExpress XtraGrid working with an unbound CheckBox colum, I eventually succeeded, but at the cost of UI consistency. So I had to go for another option... CheckedListBoxControl.

Using .NET standard CheckedListBoxControl, I couldn't find the properties DataSource, DisplayMember, and ValueMember. Probably the reason would be an older .NET Framework. So instead of getting into the hassle, I decided to use the DevExpress CheckedListBoxControl.

Below is the code for my generic methods I have used for the CheckedListBoxControl. I would like to point here that, I have used a DataView as a datasource for my CheckedListBoxControl and not simple items. So the .Items property is not of any use here but .CheckedItems, .CheckedIndices, and .ItemCount properties are used. .CheckedItems returns all the checkbox items as an object, while .CheckedIndices returns indexes of all the .CheckState = "Checked" items. I have used these indices as the rowIndex of the DataView to fetch the values from the DataView. So it is always better to use

foreach (int index in chkList.CheckedIndices)
 { ... = myDataRow[index].Row["FIELDNAME"].ToString(); ... }

to get the checked value.

[C#]
#region CheckBox Generic Methods
public void SelectAll(DevExpress.XtraEditors.CheckedListBoxControl chkList) { 
    for(int i=0;i< chkList.ItemCount;i++) {
      chkList.SetItemChecked(i, true);
    }             
}
public void RemoveAll(DevExpress.XtraEditors.CheckedListBoxControl chkList) { 
    for(int i=0;i< chkList.ItemCount;i++) {
      chkList.SetItemChecked(i, false);  
    }       
}
public bool Checked(DataView dvSource, 
      DevExpress.XtraEditors.CheckedListBoxControl chkList, 
      string keyID, string fieldName) {
  bool stat = false;
  try{
    for (int i=0; i< dvSource.Count; i++ ) {
      if (dvSource[i].Row[fieldName].ToString()  == keyID) {
        chkList.SetItemChecked (i, true);
        stat = true;
        break;
      }
    }
  }
  catch(Exception ex){
    Code.ShowMessage(ex.ToString());
 }
 return stat;
}
public bool UnChecked(DataView dvSource, 
     DevExpress.XtraEditors.CheckedListBoxControl chkList, 
     string keyID, string fieldName) {
  bool stat = false;
  try{                      
    for (int i=0; i< dvSource.Count; i++ ) {
      if (dvSource[i].Row[fieldName].ToString() == keyID.ToString()) {
        chkList.SetItemChecked (i, false);
        stat = true;
        break;
      }
    }     
  }
  catch(Exception ex){
    Code.ShowMessage(ex.ToString());
  }
  return stat;
}
#endregion