I have a datagridview fill with data from database. The first column is a checkboxcolumn (data for this column retrieved from database is type BIT) and I want the user only check one. If the user select other one, the first one have to be unchecked.
I have seen a lot of code and none works.
What I could do?
Is a Winforms C# app with SQL SERVER.
private void dataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
// Whatever index is your checkbox column
var columnIndex = 0;
if (e.ColumnIndex == columnIndex)
{
// If the user checked this box, then uncheck all the other rows
var isChecked = (bool)dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
if (isChecked)
{
foreach (DataGridViewRow row in dataGridView.Rows)
{
if (row.Index != e.RowIndex)
{
row.Cells[columnIndex].Value = !isChecked;
}
}
}
}
}
Subscribe to CellContentClick
and add dataGridView.EndEdit()
for much better user experience (cell doesn't have to lose the focus for event to be fired):
private void ChangeCheckedStateOfOtherCheckboxesInDgv(object sender, DataGridViewCellEventArgs e)
{
const int chkBoxColumnIndex = 0;
var dataGridView = (DataGridView)sender;
if (e.ColumnIndex == chkBoxColumnIndex)
{
dataGridView.EndEdit();
var isChecked = (bool)dataGridView[e.ColumnIndex, e.RowIndex].Value;
if (isChecked)
{
foreach (DataGridViewRow row in dataGridView.Rows)
{
if (row.Index != e.RowIndex)
row.Cells[chkBoxColumnIndex].Value = !isChecked;
}
}
}
}
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