DataGridViewCheckBoxCell点击处理问题

Ron*_*Ron 4 c# datagridviewcheckboxcell

我创建了一个DataGridView控件,其中第一列是一个复选框.当我在复选框内单击时,代码正确执行.但是,当单元格中出现单击但不出现复选框时,代码会正确处理复选框的状态,但不会更新复选框本身,因此它仍处于单击之前的状态.

我该如何纠正?

   private void myDataGrid_CellClick(object sender, DataGridViewCellEventArgs e)
   {
       if (e.RowIndex == -1) return; //check if row index is not selected
       DataGridViewCheckBoxCell ch1 = new DataGridViewCheckBoxCell();
       ch1 = (DataGridViewCheckBoxCell)myDataGrid.Rows[e.RowIndex].Cells[0];

       if (ch1.Value == null)
           ch1.Value = false;
       switch (ch1.Value.ToString())
       {
           case "False":

               ch1.Value = true;

               break;
           case "True":

               ch1.Value = false;
               break;
       }
      //BUT doesn't seem to matter what I do with ch1.Value. Inside the checkbox all is OK but
      //outside, no.

   }
Run Code Online (Sandbox Code Playgroud)

如果我单击该行上的另一个单元格,则会正确处理该复选框.仅当我单击复选框单元格而不是复选框本身时.

我的意思是(和道歉),代码正确执行但UI没有正确更新以反映更改.因此,如果取消选中此复选框,则在取消选中之前取消选中该复选框在此输入图像描述即使它实际上是检查过的,也是病房.

谢谢RON

Ant*_*ony 7

我不是百分之百确定是什么导致了这种行为,但我相信它与复选框单元格进入编辑模式时有关.确认,这个问题肯定是在单击单元格内部时进入编辑模式引起的.请参阅帖子末尾的编辑.

因为您自己设置单元格的值,所以只需将复选框列设置为只读即可解决此问题.

以下代码在使用LINQPad时很适合我(我看起来很自由来简化处理程序逻辑):

void Main()
{
    var dataGridView = new DataGridView();
    dataGridView.Columns.Add(new DataGridViewCheckBoxColumn());
    dataGridView.Columns.Add(new DataGridViewTextBoxColumn());
    dataGridView.Columns.Add(new DataGridViewTextBoxColumn());

    dataGridView.Columns[0].ReadOnly = true;
    dataGridView.Columns[1].ReadOnly = true;
    dataGridView.Columns[2].ReadOnly = true;

    dataGridView.CellClick += this.DataGridView_CellClick;

    dataGridView.Dump();
}

void DataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex < 0) return;

    var dataGridView = (DataGridView) sender;
    var cell = dataGridView[0, e.RowIndex];

    if (cell.Value == null) cell.Value = false;
    cell.Value = !(bool)cell.Value;
}
Run Code Online (Sandbox Code Playgroud)

我注意到的唯一奇怪之处是双击中的第二次单击不会被路由到CellClick事件处理程序.如果您确实需要此行为,则可以将相同的处理程序绑定到CellDoubleClick事件.

编辑:

如果您不喜欢将第一列设为只读,那么您只需EndEdit在更改值后添加一个调用:

void DataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex < 0) return;

    var dataGridView = (DataGridView) sender;
    var cell = dataGridView[0, e.RowIndex];

    if (cell.Value == null) cell.Value = false;
    cell.Value = !(bool)cell.Value;
    dataGridView.EndEdit();
}
Run Code Online (Sandbox Code Playgroud)

用户NeverHopeless 对另一个问题评论暗示了这一点.