سؤال

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");
}
هل كانت مفيدة؟

المحلول

What about:

foreach(DataGridViewRow row in dataGridView.Rows){
    if (row.Cells[0].Value != null && (bool)row.Cells[0].Value){
       //checked, do something
    }
}

نصائح أخرى

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top