C#DataGridView的复选框选中事件 [英] C# DataGridView Checkbox checked event
问题描述
我是新的C#,以及为它提供客人住房的旅客一个地方书我的房间的应用程序。该屏幕可以解释清楚我希望实现;
I am new to c# and making a "book my room" app for a place which provides guest housing to travelers. This screen may explain well what I wish to achieve;
这是计算雇员的每小时工资软件的.GIF:
This is a .GIF of a software which calculates hourly pay of an employee:
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;
我添加使用此复选框列;
I added the checkbox column using this;
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但没有任何工程,这将是与复选框相关联排正确的方式链接。
Whenever a user logs in from the login screen a new row will be inserted in the table and hence the dgv will be updated, with corresponding users entry. I don't understand how to link those checkboxes with datagridview I tried celldirtystatechanged but nothing works, what would be the right way to associate the row with checkbox.
推荐答案
您可以处理的 CellContentClick
你的的DataGridView事件
,把逻辑改变这些细胞中存在。
You can handle CellContentClick
event of your DataGridView
and put the logic for changing those cells there.
关键点使用的 commitEdit的(DataGridViewDataErrorContexts.Commit)
来犯当前单元格中的数据高速缓存的变化但不结束编辑模式。这时候你在这种情况下检查细胞的价值的方法,它返回当前选中或取消选中值在单元格中看到当前之后点击:
The key point is using CommitEdit(DataGridViewDataErrorContexts.Commit)
to commits changes in the current cell to the data cache without ending edit mode. This way when you check for value of cell in this event, it returns current checked or unchecked value which you see in the cell currently after click:
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
}
}
这篇关于C#DataGridView的复选框选中事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!