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");
}
Cocoa Dev
  • 9,361
  • 31
  • 109
  • 177

2 Answers2

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.

Community
  • 1
  • 1
Geoff
  • 8,551
  • 1
  • 43
  • 50
  • The CheckBoxColumn1.Name, is this the index for the column or the actual name? – Cocoa Dev Apr 22 '13 at 16:16
  • That's the name of the column – Geoff Apr 22 '13 at 16:20
  • I've never used Lists that way. Is there an easy way to use your 1 liner to get all the rows that are selected and use the selected rows are the new datasource for the datagridview (thus only showing rows that have been checked). – Cocoa Dev Apr 22 '13 at 16:26
  • [This question](http://stackoverflow.com/questions/6473326/using-a-list-as-a-datasource-for-datagridview) would be a good place to start digging into that – Geoff Apr 22 '13 at 17:00
  • I've managed to use List for my datasource. I've learnt that Datasourec looks for properties. So I had to create a class called StringValue and it is a class with a constructor that accepts a string and a Value method that returns the value of the String. But do I need to do the same thing using DataGridRow as my DataSource or will it work automagically? – Cocoa Dev Apr 22 '13 at 17:05
1

What about:

foreach(DataGridViewRow row in dataGridView.Rows){
    if (row.Cells[0].Value != null && (bool)row.Cells[0].Value){
       //checked, do something
    }
}
Omar
  • 16,329
  • 10
  • 48
  • 66
  • I tested this. I have cells with numbers 1 -> 10. I checked 1,2,3 and then created a new List and added them to the list. My NEW list only contained 1,2. 3 was missing – Cocoa Dev Apr 23 '13 at 13:34
  • If I change the word Value to State, it doesn't ever enter the loop – Cocoa Dev Apr 23 '13 at 14:37
  • My edit just formatted the code. However try by changing `(bool)(row.Cells[0]).Value` to `(bool)row.Cells[0].Value`. – Omar Apr 23 '13 at 15:41