Marking Checkboxes in Data grid View on the basis of Datatable

2.5k views Asked by At

I have a Data grid View dataGridView1 which is bind with a data table dt1.

Data table dt1 has following data:

name | status
-----+-------
abc  |   0
abd  |   1
abc  |   0
abc  |   1
abc  |   1

I am putting a check box in Data gridview and I want the default value of check box as checked where the status = 1.

DataGridViewCheckBoxColumn checkColumn = new DataGridViewCheckBoxColumn();
checkColumn.Name = "X";
checkColumn.HeaderText = "X";

dataGridView1.Columns.Add(checkColumn);

for (int x = 0; x < countSubCategory; x++)
{
    if (dt1.Rows[x].ItemArray[1].ToString() == "1")
    {
          // here I want to check the checkbox but I don't know what to write here
          checkColumn.Checked= true;
    }

    else { 
        checkColumn.Value = false; 
    }
} 
1

There are 1 answers

6
dovid On BEST ANSWER

instead

checkColumn.Checked= true;

write

DataGridName[x][position_of_checkBox_column].Value = true;

But it is better to work on the data and not on the UI.

you can add to DataTable a Column-expression.

dt1.Columns.Add(new DataColumn("X", typeof(bool), "status = 1"));

this one line, replaces all the code on the question!


Sometimes, more simple and effective, change the SQL statement.

Instead

SELECT id, status

Write

SELECT id, IIF(status = 1, true, false) AS statusBool