Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow only one checkbox selected in DataGridView

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.

like image 637
GuaGua0308 Avatar asked Feb 11 '16 21:02

GuaGua0308


2 Answers

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;
            }
         }
      }
   }
}
like image 84
Jon Avatar answered Oct 25 '22 16:10

Jon


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;
            }
        }
    }
}
like image 36
Rychu Avatar answered Oct 25 '22 17:10

Rychu