I want to handle Checked
event of CheckBox
columns in my DataGridView
and perform an operation based on column checked value (true/false). I tried to use CellDirtyStateChanged
without any success. In fact I want to detect checked change immediately after the user checks or unchecks the check box.
Here is a description about my application. 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;
This is a .GIF of a software which calculates hourly pay of an employee and this photo is an illustration of what actually I want to build:
Code for displaying my table in DataGridView
is:
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);
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.
You can handle CellContentClick
event of your DataGridView
and put the logic for changing those cells there.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With