DataGridViewCheckBoxColumn小结

来源:互联网 发布:江苏移动网络测速 编辑:程序博客网 时间:2024/05/29 18:16

1. DataGridViewCheckBoxColumn多选。

默认情况下,DataGridViewCheckBoxColumn不是Winform下的CheckBox,只是一个显示图像,所以需要通过操作缓存数据控制界面显示。

覆写OnCellValuePushed和OnCellValueNeeded方法,或添加相应事件:CellValuePushed,CellValueNeeded

下例中,CellValuePushed用于将界面勾选情况刷进缓存,CellValueNeeded用于将缓存数据显示在界面上(通过设置DataGridViewCellValue),chechState用来保存每个单元格的勾选情况。

private Dictionary<string, bool> m_checkState=new Dictionary<string, bool>();protected override void OnCellValuePushed(DataGridViewCellValueEventArgs e){    if (!checkState.ContainsKey(checkField))        checkState.Add(checkField, Convert.ToBoolean(e.Value));    else        checkState[checkField] = Convert.ToBoolean(e.Value);}protected override void OnCellValueNeeded(DataGridViewCellValueEventArgs e){if (checkState.ContainsKey(checkField))        e.Value = checkState[checkField];    else        e.Value = false;}

2. 编辑模式下提交界面数据至缓存。

只有当鼠标焦点离开勾选框后,勾选结果才会提交到数据缓存,假如勾选后直接点击列头进行列排序,因为勾选结果没有提交,排序后的多选界面相当混乱。

所以需要编辑模式下提交至缓存,使用到CurrentCellDirtyStateChanged事件。

this.CurrentCellDirtyStateChanged+=new EventHandler(GridView_CurrentCellDirtyStateChanged);private void GridView_CurrentCellDirtyStateChanged(object sender, EventArgs e){if (this.IsCurrentCellDirty){this.CommitEdit(DataGridViewDataErrorContexts.Commit);}}
CommitEdit提交编辑内容时将先调用OnCellValueNeeded,再调用OnCellValuePushed。


3.单击整行即可选中DataGridViewCheckBoxColumn。

protected override void OnCellMouseDown(DataGridViewCellMouseEventArgs e){//排除表头和复选框的所在列if (e.RowIndex >= 0 && e.ColumnIndex > 0){DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)this.Rows[e.RowIndex].Cells[0];if ((bool)cell.FormattedValue){cell.Value = false;cell.EditingCellFormattedValue = false;}else{cell.Value = true;cell.EditingCellFormattedValue = true;}}}

4.空行时不显示DataGridViewCheckBoxColumn。

空数据时,只画出边界和背景。

参考:http://stackoverflow.com/questions/7664115/c-sharp-datagridviewcheckboxcolumn-hide-gray-out

this.CellPainting+=new DataGridViewCellPaintingEventHandler(GridView_CellPainting);void GridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e){if (e.ColumnIndex == 0){//空行的复选框只画出边界和背景if (e.RowIndex >= this.DataItems.Count){e.Paint(e.ClipBounds, DataGridViewPaintParts.Border | DataGridViewPaintParts.Background); e.Handled = true;}}}


0 0
原创粉丝点击