環境:VS2013
系統:win7 32位
問題:在DataGridView中使用列樣式DataGridViewCheckBoxColumn的問題:
(1)界面上通過鼠標點擊,使DataGridViewCheckBoxColumn列的多個CheckBox狀態發生改變后,當鼠標仍選中DataGridViewCheckBoxColumn列的某個單元格時,獲取其狀態時,發現選中的單元格值獲取結果錯誤;
獲取方法:dr.Cells["CheckItem"].Value.ToString()
foreach (DataGridViewRow dr in DgvSoftUp.Rows) { if (dr.Cells["CheckItem"].Value != null) { if (Convert.ToBoolean(dr.Cells["CheckItem"].Value.ToString())) { …… } } }
解決方法(來源於http://www.cnblogs.com/gossip/archive/2008/12/02/1346047.html):
在DataGridView的CurrentCellDirtyStateChanged事件中增加:DgvSoftUp.CommitEdit(DataGridViewDataErrorContexts.Commit);
private void DgvSoftUp_CurrentCellDirtyStateChanged(object sender, EventArgs e) { DgvSoftUp.CommitEdit(DataGridViewDataErrorContexts.Commit); }
(2)通過代碼設置CheckBox狀態時,當單元格選中狀態時,狀態設置無效。
設置代碼如下:
foreach (DataGridViewRow dr in DgvSoftUp.Rows) { dr.Cells["CheckItem"].Value = true; }
解決辦法,在設置之后,增加EndEdit():
DgvSoftUp.EndEdit();