Datagridview forcing only one checkbox to be selected in a column
15,243
Solution 1
You will have to subscribe for the CellValueChanged
event of the grid and depending on the check state of the current cell, loop the DataGridView and set true/false as Value for the other cells.
void grd_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if ((sender as DataGridView).CurrentCell is DataGridViewCheckBoxCell)
{
if (Convert.ToBoolean(((sender as DataGridView).CurrentCell as DataGridViewCheckBoxCell).Value))
{
// Maybe have a method which does the
//loop and set value except for the current cell
}
}
}
Solution 2
private void grdRegClass_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (grdRegClass.Columns.IndexOf(grdRegClass.Columns["Status"]) == e.ColumnIndex)
{
int currentcolumnclicked = e.ColumnIndex;
int currentrowclicked = e.RowIndex;
foreach (DataGridViewRow dr in grdRegClass.Rows)
{
dr.Cells[currentcolumnclicked].Value = false;
}
grdRegClass.CurrentRow.Cells[currentrowclicked].Value = true;
}
}
Solution 3
private void dataGridViewProduit_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if ((sender as DataGridView).CurrentCell is DataGridViewCheckBoxCell)
{
if (Convert.ToBoolean(((sender as DataGridView).CurrentCell as DataGridViewCheckBoxCell).Value))
{
foreach (DataGridViewRow row in (sender as DataGridView).Rows)
{
if (row.Index != (sender as DataGridView).CurrentCell.RowIndex && Convert.ToBoolean(row.Cells[e.ColumnIndex].Value) == true)
{
row.Cells[e.ColumnIndex].Value = false;
}
}
}
}
}
private void dataGridViewClient_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (this.dataGridViewClient.IsCurrentCellDirty)
{
dataGridViewClient.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
Author by
TtT23
Updated on June 04, 2022Comments
-
TtT23 almost 2 years
How do I force only a single checkbox to be checked in a column of a Datagridview?