How to know if the Check box is checked

1.3k views Asked by At

In a data grid view I need to loop on the rows and get the rows that contain a checked checkbox dgv.rows[i].cells[0].value is returning empty in the both cases all this is happening on the event CellContentClick

3

There are 3 answers

1
mellamokb On

Try:

'VB
Dim MyCheckBox As CheckBox = _
    CType(dgv.rows[i].cells[0].findcontrol("checkbox_id"), CheckBox)

C#:

//C#
CheckBox MyCheckBox =
    dgv.Rows[i].Cells[0].FindControl("checkbox_id") as CheckBox;

The Value property on a cell refers to text content when the cell doesn't contain any other controls.

3
Metro Smurf On

If the checkbox does not contain any data, the result will be a null value. You can parse the value in your loop with a bool.Parse() assuming the value isn't null, i.e.,

for ( int i = 0; i < dgv.Rows.Count; i++ )
{
    var val = dgv.Rows[i].Cells[0].Value;
    if ( val == null ) { continue; }

    bool isChecked = bool.Parse( val.ToString() );
}
0
Tergiver On
static class DataGridViewExtensions
{
    public static IEnumerable<DataGridViewRow> CheckedRows(this DataGridView dgv, string checkedColumnName)
    {
        return CheckedRows(dgv, dgv.Columns[checkedColumnName].Index);
    }

    public static IEnumerable<DataGridViewRow> CheckedRows(this DataGridView dgv, int checkedColumnIndex)
    {
        foreach (DataGridViewRow row in dgv.Rows)
        {
            DataGridViewCheckBoxCell cell = row.Cells[checkedColumnIndex] as DataGridViewCheckBoxCell;
            Debug.Assert(cell != null, "The column specified is not a check box column");
            if (cell != null && (bool)cell.Value)
                yield return row;
        }
    }
}