I have a DataGridView and Checkbox column attached to it. I would like to achieve something like this, when a few checkboxes are selected, it will compare the cells value of column named Description between those selected row. If the values are not same, a message box will be show up, else the value will be parse into a textbox.
As in example above, a messagebox should be show up when those rows are selected.
This is what i have done so far and i don't know how to continue from here.
private void datagridview1_CellClick(object sender, DataGridViewCellEventArgs e)
{
foreach (DataGridViewRow r in datagridview1.Rows)
{
bool ckboxselected = !Convert.ToBoolean(r.Cells[0].Value);
if (e.RowIndex >= 0 && e.ColumnIndex == 0)
{
if (ckboxselected)
{
//compare
}
else
{
//another action
}
}
}
}
I appreciate you help!
The CellClick event is raised when you mouse-click anywhere within the cell's bounds including the CheckBox area of the DataGridViewCheckBoxCell. Also, it's raised when you press the Space key while a content cell has focus. On the other hand, the CellContentClick event is raised when a content area (i.e. CheckBox) is hit by mouse or key and the cell's Value
is about to change.
As I understand your question, you need to implement the latter to take an action if you get different descriptions (column 2) of the checked rows. If so, a simple LINQ query will do.
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0 && e.ColumnIndex == 0)
{
// To get the new value...
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
var row = dataGridView1.Rows[e.RowIndex];
var any = dataGridView1.Rows.Cast<DataGridViewRow>().Where(
r => r.Index != row.Index && (bool)r.Cells[0].FormattedValue).Any(
r => r.Cells[2].Value?.ToString().ToLower() != row.Cells[2].Value?.ToString().ToLower());
if (any)
{
// Uncomment if you need to cancel the check...
//row.Cells[0].Value = false;
//dataGridView1.EndEdit();
MessageBox.Show("Not same descriptions...");
}
else
{
// ...
}
}
}
If you need to skip the null
descriptions.
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0 && e.ColumnIndex == 0)
{
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
var row = dataGridView1.Rows[e.RowIndex];
if (row.Cells[2].Value == null) return;
var any = dataGridView1.Rows.Cast<DataGridViewRow>().Where(
r => r.Index != row.Index && (bool)r.Cells[0].FormattedValue && r.Cells[2].Value != null).Any(
r => r.Cells[2].Value.ToString().ToLower() != row.Cells[2].Value.ToString().ToLower());
if (any)
{
// Uncomment if you need to uncheck...
//row.Cells[0].Value = false;
//dataGridView1.EndEdit();
MessageBox.Show("Not same descriptions...");
}
else
{
// ...
}
}
}
Trim .ToLower()
calls for the case-sensitive comparisons.