Lady_A Lady_A - 1 year ago 73
C# Question

c# datagridview check boxes

I am pulling data from a database and based on the values i get from the table i want to check the checkboxes.

All this needs to be processed before the user can see the gridview, so i have put this piece of code in the load method but i am struggling to change the checkbox status based on the data.

The '**' part of the code is where i am having problems.

my code so far:

using(getConnection.sqlCmd = new SqlCommand(sqlQuery,getConnection.sqlcon))
{
using(var reader = getConnection.sqlCmd.ExecuteReader())
{
while (reader.Read())
{
col1 = reader.GetValue(0).ToString();
**foreach(DataGridView row in dgvAccident.Rows)
{
DataGridViewCheckBoxCell chk = dgvAccident.Rows[0].Cells[4] as DataGridViewCheckBoxCell;
if (col1.Equals('Y'))
chk.Selected = true;
else
chk.Selected = false;
}**
}

}
}

Answer Source

Use Value property of DataGridViewCell instead of Selected

 foreach(DataGridView row in dgvAccident.Rows)
 {
     dgvAccident.Rows[0].Cells[4].Value = (col1.Equals('Y'));
 }

but your code seems off. You will re-check all rows checkboxes with each row returned from DB. You should probably check if DataGridView row corresponds to row returned from DB and then check value.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download