2015-04-01 80 views
1

我用处理我的复选框单击事件CurrentCellDirtyStateChanged。当我点击包含复选框的单元格时,即我单击单元格时,选中该复选框并调用DirtyStateChanged,我希望能够处理同一个事件。使用下面的代码并没有多大帮助,它甚至不会调用当前的CellDirtyStateChanged的。我已经用完了想法。单击单元格时检查Datagridview复选框

private void dataGridView_CellClick(object sender, DataGridViewCellEventArgs e) 
{ 
    if(dataGridView.Columns[e.ColumnIndex].ReadOnly != true) 
    {  
      //option 1 
      (dataGridView.CurrentRow.Cells[e.ColumnIndex] as DataGridViewCheckBoxCell).Value = true; 
      //option 2 
      DataGridViewCheckBoxCell cbc = (dataGridView.CurrentRow.Cells[e.ColumnIndex] as DataGridViewCheckBoxCell); 
      cbc.Value = true; 
      //option 3 
      dataGridView.CurrentCell.Value = true; 
    } 

} 
+0

这是XAML吗?这将是一个比[单元]和[检查]更好的问题标签 – DLeh 2015-04-01 20:51:15

+0

为什么这个问题会得到一个负面投票? – Jnr 2015-04-03 11:34:05

回答

6

由于Bioukh指出,必须调用NotifyCurrentCellDirty(true)触发事件处理程序。但是,添加该行将不再更新您的选中状态。要完成您选中的状态更改,请点击,我们将添加致电RefreshEdit。这将在单击单元格时切换单元格检查状态,但它也会使实际复选框的第一次单击有点bug。所以我们添加如下所示的CellContentClick事件处理程序,你应该很好去。


private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) 
{ 
    DataGridViewCheckBoxCell cell = this.dataGridView1.CurrentCell as DataGridViewCheckBoxCell; 

    if (cell != null && !cell.ReadOnly) 
    { 
    cell.Value = cell.Value == null || !((bool)cell.Value); 
    this.dataGridView1.RefreshEdit(); 
    this.dataGridView1.NotifyCurrentCellDirty(true); 
    } 
} 

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) 
{ 
    this.dataGridView1.RefreshEdit(); 
} 
+0

感谢您的回复。我得到'指定的强制转换无效'异常:(bool)cell.value – Jnr 2015-04-03 11:31:15

+0

@Jnr如果不是'True'或'False',单元格的值是多少? – OhBeWise 2015-04-03 12:50:26

+1

这是个好问题,我没有提到datagridview是数据绑定的。所以这个值是DBNull。我使用dataGridView.CurrentCell.Value = true;而不是使用cast来布尔, 感谢您的帮助! – Jnr 2015-04-04 13:57:44

0

这应该做你想要什么:

private void dataGridView_CellClick(object sender, DataGridViewCellEventArgs e) 
{ 
    if(dataGridView.Columns[e.ColumnIndex].ReadOnly != true) 
    {  
     dataGridView.CurrentCell.Value = true; 
     dataGridView.NotifyCurrentCellDirty(true); 
    } 
} 
0
private void dataGridView3_CellClick(object sender, DataGridViewCellEventArgs e) 
    { 
     if (e.ColumnIndex == dataGridView3.Columns["Select"].Index)//checking for select click 
     { 
      dataGridView3.CurrentCell.Value = dataGridView3.CurrentCell.FormattedValue.ToString() == "True" ? false : true; 
      dataGridView3.RefreshEdit(); 
     } 
    } 

这些变化都为我工作!

相关问题