C#正确实现DataGridView中复选框(CheckBox)全选和反选

曾经以为直接修改Value值即可,但是试过的朋友都会知道,当鼠标选中某一个复选框所在的单元格的时候我们进行全选和反选这个单元格是不受影响的,也就是说比如有10行数据,我们选中了其中一行的复选框所在单元格再进行全选的话只能影响到9行。原因是没有结束状态的单元格是不受其他操作影响的,也就是其他操作对他无效,所以只要手动结束他的编辑状态就可以了。

原作者链接

private void 全选AltAToolStripMenuItem_Click(object sender, EventArgs e)
{
    if (dataGridView1.Rows.Count > 0)
    {
        dataGridView1.EndEdit();//停止编辑状态
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            row.Cells[0].Value = true;
        }
    }
}
       
private void 反选CtrlFToolStripMenuItem_Click(object sender, EventArgs e)
{
    if (dataGridView1.Rows.Count > 0)
    {
        dataGridView1.EndEdit();//结束编辑状态
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            row.Cells[0].Value = !(true.Equals(row.Cells[0].Value));
                   
        }
    }
}
View Code

 

posted @ 2022-04-30 11:36  秋天的林子  阅读(2330)  评论(0编辑  收藏  举报