Winform 中DataGridView的checkbox列,当修改checkbox状态时实时获得其状态值

Winform 中DataGridView的checkbox列,当修改checkbox状态时实时获得其状态值

     不知道大家有没有这样的经验,当点击或者取消datagridview的checkbox列时,比较难获得其状态是选中还是未选中,进而不好进行其它操作,下面就列出它的解决办法:

   主要用到了DataGridView的CurrentCellDirtyStateChanged和CellValueChanged两个事件

   CurrentCellDirtyStateChanged事件是提交对checkbox状态的修改

     CellValueChanged事件是当状态提交后,也就是单元格值改变后做一些其它的操作

    (1). CurrentCellDirtyStateChanged事件代码:

复制代码
void PositionListDataView_CurrentCellDirtyStateChanged( object sender, EventArgs e) 
        { 
            DataGridView grid = sender as DataGridView;
              if (grid != null ) 
            { 
                grid.CommitEdit(DataGridViewDataErrorContexts.Commit); 
            } 
        }
复制代码

 

  (2). CellValueChanged事件代码: 

复制代码
void PositionListDataView_CellValueChanged( object sender, DataGridViewCellEventArgs e)
        {
            DataGridView grid = sender as DataGridView;
             if (grid != null && e.RowIndex >= 0 )
            {
                if (grid.Columns[e.ColumnIndex].Name == " Check " )
                {
                    DataTable dt = grid.DataSource as DataTable;
                     int pstnID = Convert.ToInt32(dt.Rows[e.RowIndex][ 1 ]);
                    
                    DataGridViewCheckBoxCell checkbox = grid.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewCheckBoxCell; // 获得checkbox列单元格
                    int result = 0 ;
                     if (checkbox != null && checkbox.Value.ToString() == " 1 " )
                    {
                        result   = cuttingReport.UpdateR_RptRstnStandardAndBlendByCheck( this .reportID,pstnID, 1 , 0 );
                    }
                    else
                    {
                        result = cuttingReport.UpdateR_RptRstnStandardAndBlendByCheck( this .reportID, pstnID, 0 , 0 );
                    }
                    if (result < 1 )
                    {
                        MessageBox.Show( " 修改失败" , " 提示" , MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }

        }
复制代码

另外:grid.Columns[e.ColumnIndex].Name == "Check" 中Name的值,是在生成DataGridView的Columns时添加的:

new DataGridViewCheckBoxColumn() { HeaderText = "Check", DataPropertyName = "Checked", Visible = true, Width = 45, Frozen = true, Name = "Check", TrueValue = 1, FalseValue = 0, IndeterminateValue = 0 }

  原文参考:http://www.cnblogs.com/gossip/archive/2008/12/02/1346047.html

转载于:https://www.cnblogs.com/gaowei-bky/p/4619135.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值