检查DataGridView上的所有复选框项

use*_*667 4 c# checkbox datagridview winforms

这是场景.

我有checkbox(名称:"全部检查"ID:chkItems)和datagridview.当我点击这个复选框时,datagridview也会检查遗嘱上的所有复选框.

我还在网格上添加了复选框列.

DataGridViewCheckBoxColumn CheckboxColumn = new DataGridViewCheckBoxColumn();
CheckBox chk = new CheckBox();
CheckboxColumn.Width = 20;
GridView1.Columns.Add(CheckboxColumn);
Run Code Online (Sandbox Code Playgroud)

这是复选框背后的代码.有一个问题row.Cell

private void chkItems_CheckedChanged(object sender, EventArgs e)
{
    foreach (DataGridViewRow row in GridView1.Rows)
    {
        DataGridViewCheckBoxCell chk = e.row.Cells(0);
        if (chk.Selected == false)
        {
            row.Cells(0).Value = true;
        }
    }
}   
Run Code Online (Sandbox Code Playgroud)

已解决(这是解决方案)

private void chkItems_CheckedChanged(object sender, EventArgs e)
{   
    foreach (DataGridViewRow row in GridView1.Rows)
    {
        DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[1];
        if (chk.Selected == false)
        {
            chk.Selected = true;
        }
    } 
}   
Run Code Online (Sandbox Code Playgroud)

Nik*_*vic 15

DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell) row.Cells[0];
Run Code Online (Sandbox Code Playgroud)

代替

DataGridViewCheckBoxCell chk = e.row.Cell(0);
Run Code Online (Sandbox Code Playgroud)

*编辑:*我认为你真的想这样做:

foreach (DataGridViewRow row in dataGridView1.Rows)
{
       DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell) row.Cells[0];
       chk.Value = !(chk.Value == null ? false : (bool) chk.Value); //because chk.Value is initialy null
}
Run Code Online (Sandbox Code Playgroud)