DataGridView - how can I make a checkbox act as a radio button?

前端 未结 4 1310
后悔当初
后悔当初 2021-01-21 00:18

I have a Windows Forms app that displays a list of objects in a DataGridView.

This control renders bool values as checkboxes.

There\'s a set of three checkboxe

4条回答
  •  执笔经年
    2021-01-21 01:19

    It would get too easy here:

    Conisder your checkbox column is the 2nd column in your datagridview.

    private void YourDatagridview_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
             if (IsHandleCreated)
            {
                if (YourDatagridview.CurrentCell == YourDatagridview.Rows[e.RowIndex].Cells[1])
                {
                    if (Convert.ToBoolean(YourDatagridview.CurrentCell.Value) == true)
                    {
                        for (int i = 0; i < YourDatagridview.RowCount; i++)
                        {
                            if (YourDatagridview.Rows[i].Cells[1] != YourDatagridview.CurrentCell)
                            {
                                YourDatagridview.Rows[i].Cells[1].Value = false;
                            }
                        }
                    }
                }
            }
        }
    

    And call this too:

    private void YourDatagridview_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (this.YourDatagridview.IsCurrentCellDirty)
            {
                YourDatagridview.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }
        }
    

    and Voila!!

提交回复
热议问题