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
How to know if the Check box is checked
1.3k views Asked by Mario At
3
There are 3 answers
3
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
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;
}
}
}
Try:
C#:
The Value property on a cell refers to text content when the cell doesn't contain any other controls.