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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM