sudhakarssd
sudhakarssd

Reputation: 451

how to check whether checkbox is checked in datagridview column

I have a Datagridview within a windows form which loads data. I have also included a checkbox column to this Datagridview in run time. My question is how can i know if any of the checkboxs from the checkbox column has been checked, and if a checkbox has been checked enable a button. I have used CellValueChanged event to perform above task but unable to get the desired result.

This is what i have done

 List<int> ChkedRow = new List<int>();

        for (int i = 0; i <= Datagridview1.RowCount - 1; i++)
        {
            if (Convert.ToBoolean(Datagridview1.Rows[i].Cells["chkcol"].Value) == true)
            {
                button1.Enabled = true;
            }
            else
            {
                button1.Enabled = false;
            }

        }

Upvotes: 1

Views: 23122

Answers (2)

Jade
Jade

Reputation: 2992

Try this code

button1.Enabled = false;
foreach (DataGridViewRow row in Datagridview1.Rows)
{
    if (((DataGridViewCheckBoxCell)row.Cells["chkcol"]).Value)
      {
        button1.Enabled = true;
        break;
      }

}

or

//This will always call the checking of checkbox whenever you ticked the checkbox in the datagrid
private void DataGridView1_CellValueChanged(
    object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == [Your column index])
       CheckForCheckedValue();
}

private void CheckForCheckedValue()
{
   button1.Enabled = false;
   foreach (DataGridViewRow row in Datagridview1.Rows)
   {
    if (((DataGridViewCheckBoxCell)row.Cells["chkcol"]).Value)
      {
        button1.Enabled = true;
        break;
      }
   }
}

NOTE Don't forget to check the for Null value and do something if it is NULL

Upvotes: 0

Damith
Damith

Reputation: 63065

set false before the loop

button1.Enabled = false;

when you found checked item, set it as Enabled true and break the loop

button1.Enabled = true;
break;

code:

button1.Enabled = false;
for (int i = 0; i <= Datagridview1.RowCount - 1; i++)
{

    if (Convert.ToBoolean(Datagridview1.Rows[i].Cells["chkcol"].Value))
    {
        button1.Enabled = true;
        break;
    }
}

Or you can do below as well

button1.Enabled = false;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
   DataGridViewCheckBoxCell cell = row.Cells[colCheckIndex] as DataGridViewCheckBoxCell;
   if (cell.Value == cell.TrueValue){
      button1.Enabled = true;
      break;
    }
}

Upvotes: 1

Related Questions