Rob*_*ett 4 c# checkbox datagridview winforms
我想处理我Checked的CheckBox列事件DataGridView并根据列检查值(true/false)执行操作.我尝试使用CellDirtyStateChanged没有任何成功.事实上,我想在用户选中或取消选中复选框后立即检测已检查的更改.
这是关于我的应用程序的描述.我是c#的新手,并为一个为旅行者提供住宿的地方制作了"预订我的房间"应用程序.这个屏幕可以很好地解释我希望实现的目标;
这是一个计算员工每小时工资的软件.GIF,这张照片说明了我想要构建的内容:

显示我的表格的代码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;
Run Code Online (Sandbox Code Playgroud)
我使用这个添加了复选框列;
DataGridViewCheckBoxColumn checkColumn = new DataGridViewCheckBoxColumn();
checkColumn.Name = "logout";
checkColumn.HeaderText = "Logout";
checkColumn.Width = 50;
checkColumn.ReadOnly = false;
checkColumn.FillWeight = 10;
dataGridView1.Columns.Add(checkColumn);
Run Code Online (Sandbox Code Playgroud)
每当用户从登录屏幕登录时,将在表中插入新行,因此将更新dgv,并输入相应的用户.我不明白如何将这些复选框与datagridview链接我尝试celldirtystatechanged但没有任何作用,将行与复选框关联的正确方法是什么.
您可以处理您的CellContentClick事件DataGridView并将逻辑用于更改那些单元格.
关键点是使用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
}
}
Run Code Online (Sandbox Code Playgroud)