Datagridview forcing only one checkbox to be selected in a column

后端 未结 9 1273
野性不改
野性不改 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: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!

提交回复
热议问题