Winform DataGridView CheckBoxColumn c# 单选 解决方案

这个问题由来已久,我最近在工作中也遇到了这个问题,不过属于这个问题比较简单初级的涉及。

发现网上对这个问题的解决方案很多不对,答非所问。

所以这里将我测试成功的解决方案记录下来。

首先,DataGridView  CheckBoxColumn 默认是可以多选,不能单选的。

所以无法通过设置来解决,必须通过代码自己控制。

而具体使用哪个事件,哪种逻辑也有很多的选择。

我自己测试,试用了DataGridView1_CellClick事件,DataGridView1_DataBindingComplete事件,

DataGridView1_DataValueChanged事件,DataGridView1_CellContentClick事件,

最终只有DataGridView1_CellContentClick这个事件成功解决了这个问题。

再说下我遇到这个问题具体情况,很简单,只有一列CheckBoxColumn,行数不限,要求一次能选一行,且当前行一旦选中,其它行取消选中。

代码如下(Winform C#语言):

复制代码
private void DataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (this.DataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].GetType() == typeof(DataGridViewCheckBoxCell))
            {
                for (int i = 0; i < this.DataGridView1.RowCount; i++)
                {
                    this.DataGridView1.Rows[i].Cells[e.ColumnIndex].Value = false;
                }
                this.DataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = true;
            }
        }

posted on 2013-07-05 09:08  GoodluckWorld  阅读(758)  评论(0编辑  收藏  举报