Datagridview forcing only one checkbox to be selected in a column

后端 未结 9 1263
野性不改
野性不改 2020-12-21 07:29

How do I force only a single checkbox to be checked in a column of a Datagridview?

相关标签:
9条回答
  • 2020-12-21 08:14

    You can set the VirtualMode setting to TRUE on the DGV to allow only one checkbox. and you can set VirtualMode setting to FALSE on the DatagridView to check more than one.

    I think this is the easiest way for the solution.

    0 讨论(0)
  • 2020-12-21 08:24

    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
                }
            }
    }
    
    0 讨论(0)
  • 2020-12-21 08:24

    You can use CellEndEdit event of DGV, as it occurs after when the cell is modified. Kindly read the comments in below code snippet to use the code below:

    private void dgrvUserProfileView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
        int CheckedCount = 0;
    
        //Make sure you have set True Value/ false Value property of check box column to 1/0 or true/false resp.
        //Lets say your column 5th(namely Department) is a checked box column
        if (dgrvUserProfileView.Columns[e.ColumnIndex].Name == "Department")
        {
            for (int i = 0; i <= dgrvUserProfileView.Rows.Count - 1; i++)
            {
                if (Convert.ToBoolean(dgrvUserProfileView.Rows[i].Cells["Department"].Value) == true)
                {
                    CheckedCount = CheckedCount + 1;
                }
            }
    
            if (CheckedCount == 1)
            {
                for (int i = 0; i <= dgrvUserProfileView.Rows.Count - 1; i++)
                {
                    if (Convert.ToBoolean(dgrvUserProfileView.Rows[i].Cells["Department"].Value) == true)
                    {
                        dgrvUserProfileView.Rows[i].Cells["Department"].ReadOnly = true;
                    }
                }
            }
            else
            {
                for (int i = 0; i <= dgrvUserProfileView.Rows.Count - 1; i++)
                {
                    dgrvUserProfileView.Rows[i].Cells["Department"].ReadOnly = false;
                }
            }
        }
    }
    

    Hope this helps!

    0 讨论(0)
提交回复
热议问题