0

My datagridview has 2 columns. Column 0 has contains checkboxes in the off position (default). The user can click the box and change the state or Checked.

How can I loop thru and find the ones that are checked. Here is my code

try
{
   // This line will cause InvalidCastException
   // Specified cast is not valid.
   if ((bool)(row.Cells[0]).Value || (CheckState)row.Cells[0].Value == CheckState.Checked)
   {
      // Do something
      MessageBox.Show("Checked");
   }
}
catch (NullReferenceException nre)
{
   MessageBox.Show("No Rows Have Been Checked");
}
4

2 回答 2

1

See the one-liner from this answer:

List<DataGridViewRow> list = DataGridView1.Rows.Cast<DataGridViewRow>().Where(k => Convert.ToBoolean(k.Cells[CheckBoxColumn1.Name].Value) == true).ToList();

That will give you a list of all rows which have the checkbox checked.

于 2013-04-22T15:45:36.553 回答
1

What about:

foreach(DataGridViewRow row in dataGridView.Rows){
    if (row.Cells[0].Value != null && (bool)row.Cells[0].Value){
       //checked, do something
    }
}
于 2013-04-22T15:50:54.947 回答