2015-12-04 79 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' –