2015-12-04 80 views
3

我想處理Checked事件CheckBox列在我的DataGridView並根據列選中的值(true/false)執行操作。我試圖使用CellDirtyStateChanged沒有任何成功。事實上,我想在用戶選中或取消選中複選框後立即檢測選中的更改。C#DataGridView複選框選中事件

這裏是關於我的應用程序的描述。我是C#的新手,爲旅行者提供賓客住所的地方「預訂我的房間」應用程序。這個屏幕可能很好地解釋我希望達到的目標;

這是一個.GIF of a software,其計算僱員的時薪和這張照片是其實我想建立一個例證: This Photo is an illustration of what actually i want to build

代碼爲DataGridView顯示我的表:

OleDbConnection connection = new OleDbConnection(); 
connection.Open(); 
OleDbCommand command = new OleDbCommand(); 
command.Connection = connection; 
string query = "select id,cusid,cusname,timein, 
timeout,duration,amount,remark from entry"; 
command.CommandText = query; 
OleDbDataAdapter da = new OleDbDataAdapter(command); 
DataTable dt = new DataTable(); 
da.Fill(dt); 
dataGridView1.DataSource = dt; 

我用這個添加了複選框列;

DataGridViewCheckBoxColumn checkColumn = new DataGridViewCheckBoxColumn(); 
checkColumn.Name = "logout"; 
checkColumn.HeaderText = "Logout"; 
checkColumn.Width = 50; 
checkColumn.ReadOnly = false; 
checkColumn.FillWeight = 10; 
dataGridView1.Columns.Add(checkColumn); 

每當用戶從登錄屏幕新行會在表中,因此DGV插入登錄將被更新,以對應使用者條目。 我不明白如何將這些複選框與datagridview關聯我試過celldirtystatechanged但沒有任何作用,將行與複選框相關聯的正確方法是什麼。

+0

您可以處理''你的DataGridView'事件CellContentClick'放在那裏改變那些細胞的邏輯。 –

回答

5

您可以處理DataGridViewCellContentClick事件,並將更改這些單元格的邏輯放在那裏。

關鍵是使用CommitEdit(DataGridViewDataErrorContexts.Commit)將當前單元格中的更改提交到數據高速緩存而不結束編輯模式。這時候你在這種情況下檢查細胞的價值的方法,它返回當前選中或您在單元格中看到未選中的值目前點擊後:

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) 
{ 
    //We make DataGridCheckBoxColumn commit changes with single click 
    //use index of logout column 
    if(e.ColumnIndex == 4 && e.RowIndex>=0) 
     this.dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit); 

    //Check the value of cell 
    if((bool)this.dataGridView1.CurrentCell.Value == true) 
    { 
     //Use index of TimeOut column 
     this.dataGridView1.Rows[e.RowIndex].Cells[3].Value = DateTime.Now; 

     //Set other columns values 
    } 
    else 
    { 
     //Use index of TimeOut column 
     this.dataGridView1.Rows[e.RowIndex].Cells[3].Value = DBNull.Value; 

     //Set other columns values 
    } 
} 
+0

這工作只需要添加this.dataGridView1.CellContentClick + =新的System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellContentClick); 給我的設計師來源 –

+0

是的,你可以使用代碼來完成,或者使用設計器。要使用設計器添加它,您可以在設計器上選擇網格,然後按F4查看屬性,在屬性窗口中,從工具條中選擇事件並在事件列表中雙擊'CellContentClick' –