Reputation: 6651
I have a datagridview with one DataGridViewCheckBoxColumn and some other TextBox Columns. I want to loop through each cell and see if the checkbox is checked then do something. I am using the following looping method. Is there a better way to do??
I have used or condition because in some computers it brings .Value
as Checked and in some it bring .Value
as true.
foreach (DataGridViewRow row in dataGridView.Rows)
{
if ((bool)(row.Cells["Checkbox"]).Value || (CheckState)row.Cells["Checkbox"].Value == CheckState.Checked)
{
// Do something
}
}
Thanks in advance.
Upvotes: 4
Views: 23387
Reputation: 6651
It worked for me using following code:
foreach (DataGridViewRow row in dgv_labelprint.Rows)
{
if (value.Value == null)
{
}
else
if ((Boolean)((DataGridViewCheckBoxCell)row.Cells["CheckBox"]).FormattedValue)
{
//Come inside if the checkbox is checked
//Do something if checked
}
}
Upvotes: 2
Reputation: 53
int subId;
List<int> olist= new List<int>();
for (int i = 0; i < gvStudAttend.Rows.Count; i++)
{
bool Ischecked = Convert.ToBoolean(gvStudAttend.Rows[i].Cells["Attendance"].Value);
if (Ischecked == true)
{
subId = gvStudAttend.Rows[i].Cells["SubjectID"].Value.ToString();
olist.Add(subId );
}
}
Upvotes: 0
Reputation: 4129
i think this will be faster than foreach
for (int i = 0; i < dataGridView.Rows.Count -1; i++)
{
DataGridViewRow row = dataGridView.Rows[i];
if ((bool)(row.Cells["Checkbox"]).Value
|| (CheckState)row.Cells["Checkbox"].Value == CheckState.Checked)
{
// Do something
}
}
Upvotes: 5
Reputation: 11090
Have a look at this link DirtyCellChanged You can then keep track of which rows have been checked and do your work, rather than having to loop through the whole table.
This event is useful when dealing with checkboxes as users sometimes click check, and then don't commit the edit by clicking somewhere else.
It's worked good for me in the past.
Upvotes: 1