日期:2014-05-18  浏览次数:20921 次

datagridview checkbox实时操作的问题
问个问题 :
  datagridview增加了一列checkbox ,但是发现无法准确去定义其选中或未选中的事件(网上查了一下好像是说离开当前焦点时才会提交操作的结果),但是我想实时改变checkbox时实时触发事件 怎么弄呢?

好像是说要用CurrentCellDirtyStateChanged事件和CellValueChanged事件的集合才可以达到预期的,该怎么写呢?

我看以一些资料:有一篇写的好像不错:

01.dgvDownloadList.CurrentCellDirtyStateChanged += new EventHandler(dgvDownloadList_CurrentCellDirtyStateChanged);  
02. dgvDownloadList.CellValueChanged += new DataGridViewCellEventHandler(dgvDownloadList_CellValueChanged);  
03.  
04.void dgvDownloadList_CurrentCellDirtyStateChanged(object sender, EventArgs e)  
05.{  
06. if (dgvDownloadList.IsCurrentCellDirty)  
07. {  
08. dgvDownloadList.CommitEdit(DataGridViewDataErrorContexts.Commit);  
09. }  
10.}  
11.  
12.void dgvDownloadList_CellValueChanged(object sender, DataGridViewCellEventArgs e)  
13.{  
14. if (dgvDownloadList.Rows.Count > 0)  
15. {  
16. for (int i = 0; i < dgvDownloadList.Rows.Count; i++)  
17. {  
18. string _selectValue = dgvDownloadList.Rows[i].Cells["Column1"].EditedFormattedValue.ToString();  
19. if (_selectValue == "True")  
20. //如果CheckBox已选中,则在此处继续编写代码  
21. }  
22. }  
23.}  

但我的问题是我写的是winform程序,上面的两个委托写在哪里呢??


因为我发现我窗口刚打开的时候(初始化),这个datagridview就会被写入默认值,这个时候就会去触发上面的valuechange事件,导致有些变量为null时(还没有初始化完毕),valuechange事件出错;


不知道我说的有没有明白?就是如何实时改变datagridview的checkbox列的某一个checkbox的状态时实时的非常准确的去触发事件??

------解决方案--------------------
datagridview本身就有cellvaluechanged事件,在那双击即可
------解决方案--------------------
C# code

private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e) 
   { 
     if (this .dataGridView1.IsCurrentCellDirty)
         { 
         this .dataGridView1.CommitEdit(DataGridViewDataErrorContexts .Commit); 
         } 
   }