Winform中 DataGridView控件中的 CheckBox 的值读出来 始终 为 False ,已解决

        private void DGV_DetailsViewer_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex.Equals(5))
            {
                DataGridViewCheckBoxCell cbx = (DataGridViewCheckBoxCell)this.DGV_DetailsViewer.Rows[e.RowIndex].Cells[e.ColumnIndex];

                MessageBox.Show(cbx.FormattedValue.ToString());
            }
        }

用的 以上这段代码 读出来 的checkBoxCell的值始终 为 False, 原因 不明。

原因是 :CellContentClick 事件 并不能修改 CheckBoxCell的值,靠 这个事件 不行。

正确的做法 应该是 利用 CurrentCellDirtyStateChanged 事件 和 CellValueChanged 事件 的 组合 来完成 这个功能。代码如下:

//这个事件先执行,即使得 修改后的 checkboxcell的内容立刻生效,否则只有离开这个单元格时 才会生效。     
   private void DGV_DetailsViewer_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (DGV_DetailsViewer.IsCurrentCellDirty)
            {
                DGV_DetailsViewer.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }
        }

//值修改后,就执行这个事件,想要实现的功能 在这个事件里实现
 private void DGV_DetailsViewer_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.RowIndex != -1 && !this.DGV_DetailsViewer.Rows[e.RowIndex].IsNewRow)
            {

                if (e.ColumnIndex.Equals(5))
                {
                    DataGridViewCheckBoxCell cbx = (DataGridViewCheckBoxCell)this.DGV_DetailsViewer.Rows[e.RowIndex].Cells[e.ColumnIndex];

                    MessageBox.Show(cbx.FormattedValue.ToString());
                }
            }
        }

猜你喜欢

转载自www.cnblogs.com/Chendezhou/p/8981632.html
今日推荐