2015-04-01 79 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(); 
     } 
    } 

這些變化都爲我工作!

相關問題