Winform 中DataGridView的checkbox列,當修改checkbox狀態時實時得到其狀態值

Winform 中DataGridView的checkbox列,當修改checkbox狀態時實時得到其狀態值

     不知道你們有沒有這樣的經驗,當點擊或者取消datagridview的checkbox列時,比較難得到其狀態是選中仍是未選中,進而很差進行其它操做,下面就列出它的解決辦法:html

   主要用到了DataGridView的CurrentCellDirtyStateChanged和CellValueChanged兩個事件post

   CurrentCellDirtyStateChanged事件是提交對checkbox狀態的修改this

     CellValueChanged事件是當狀態提交後,也就是單元格值改變後作一些其它的操做spa

    (1). CurrentCellDirtyStateChanged事件代碼:code

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

 

  (2). CellValueChanged事件代碼: orm

複製代碼
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時添加的:htm

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

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

相關文章
相關標籤/搜索