Looping through datagridview and reading the CheckBoxColumn value
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 s开发者_StackOverflow中文版omething
}
}
Thanks in advance.
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
}
}
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
}
}
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.
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 );
}
}
精彩评论