How to: Use CheckEdit to Display and Modify Data from Bound Data Field

  • 3 minutes to read

This example demonstrates how to handle RepositoryItemCheckEdit.QueryCheckStateByValue and RepositoryItemCheckEdit.QueryValueByCheckState events in order to use a check editor to display and modify data from the bound data field.

The example assumes that a check editor is bound to a specific dataset field whose type is not obviously known and should be determined programmatically. The available data types that the field can take on are boolean, string and integer. So the field can contain the following combinations representing an option value (these values will be used to set the editor's CheckEdit.EditValue property):

  • True, False - for the boolean type;
  • "Yes", "No", "?" - for the string type;
  • 1, 0, -1 - for the integer type.

It is evident that making use of RepositoryItemCheckEdit.ValueChecked, RepositoryItemCheckEdit.ValueUnchecked and RepositoryItemCheckEdit.ValueGrayed properties is insufficient in this case. Thus, the example requires and implements a custom "edit value -> check state" and "check state -> edit value" conversion logic, which is illustrated by the sample code below.

using DevExpress.XtraEditors.Controls;

private void checkEdit1_QueryCheckStateByValue(object sender, QueryCheckStateByValueEventArgs e) {
    string val = e.Value.ToString();
    switch (val) {
        case "True":
        case "Yes":
        case "1":
            e.CheckState = CheckState.Checked;
            break;
        case "False":
        case "No":
        case "0":
            e.CheckState = CheckState.Unchecked;
            break;
        default:
            e.CheckState = CheckState.Indeterminate;
            break;
    }
    e.Handled = true;
}

private void checkEdit1_QueryValueByCheckState(object sender, QueryValueByCheckStateEventArgs e) {
    CheckEdit edit = sender as CheckEdit;
    object val = edit.EditValue;
    switch (e.CheckState) {
        case CheckState.Checked:
            if (val is bool) e.Value = true;
            else if (val is string) e.Value = "Yes";
            else if (val is int) e.Value = 1;
            else e.Value = null;
        break;
        case CheckState.Unchecked:
            if (val is bool) e.Value = false;
            else if (val is string) e.Value = "No";
            else if (val is int) e.Value = 0;
            else e.Value = null;
            break;
        default:
            if (val is bool) e.Value = false;
            else if (val is string) e.Value = "?";
            else if (val is int) e.Value = -1;
            else e.Value = null;
            break;
    }
    e.Handled = true;
}