DataGridView - 如何使复选框充当单选按钮?

Che*_*eso 3 c# datagridview winforms

我有一个Windows窗体应用程序,它显示DataGridView中的对象列表.

此控件将bool值呈现为复选框.

对象属性中有一组三个相互排斥的复选框.最多其中一个可能是真的.因此,我希望复选框的行为类似于一组单选按钮.

只是老家伙的一个侧面评论:我认为这些天人们甚至不知道为什么这些被称为单选按钮.在过去,汽车中的收音机有4或5个按钮,按下任何一个按钮都会导致所有其他按钮弹出.它们是相互排斥的.这些天"单选按钮"可能不是一个有用的描述,因为无线电不再有这样的按钮,我不认为.

我该怎么做?我想如果我将"CheckedChanged"事件附加到复选框,我知道该行,我将能够找到所有其他复选框.

在首次渲染时,我可以挂钩什么事件来抓住复选框控件,以便我可以将CheckedChanged事件附加到它?我知道DataGridView.CellFormatting,但我认为这是错误的,因为每次DataGridView绘制时都会调用它.我真的需要一个仅在第一次呈现DGV时调用的事件.

Che*_*eso 7

感谢KeithS提供了有用的答案.

当我在文档中查找CellValueChanged时,我发现这个有用的一点:

提交用户指定的值时会发生DataGridView.CellValueChanged事件,这通常在焦点离开单元格时发生.

但是,对于复选框单元格,您通常希望立即处理更改.要在单击单元格时提交更改,您必须处理DataGridView.CurrentCellDirtyStateChanged事件.在处理程序中,如果当前单元格是复选框单元格,则调用DataGridView.CommitEdit方法并传入Commit值.

这是我用来获取无线电行为的代码:

    void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
    {
        // Manually raise the CellValueChanged event
        // by calling the CommitEdit method.
        if (dataGridView1.IsCurrentCellDirty)
        {
            dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
        }
    }

    public void dataGridView1_CellValueChanged(object sender,
                                               DataGridViewCellEventArgs e)
    {
        // If a check box cell is clicked, this event handler sets the value
        // of a few other checkboxes in the same row as the clicked cell.
        if (e.RowIndex < 0) return; // row is sometimes negative?
        int ix = e.ColumnIndex;
        if (ix>=1 && ix<=3)
        {
            var row = dataGridView1.Rows[e.RowIndex];

            DataGridViewCheckBoxCell checkCell =
                (DataGridViewCheckBoxCell) row.Cells[ix];

            bool isChecked = (Boolean)checkCell.Value;
            if (isChecked)
            {
                // Only turn off other checkboxes if this one is ON. 
                // It's ok for all of them to be OFF simultaneously.
                for (int i=1; i <= 3; i++)
                {
                    if (i != ix)
                    {
                        ((DataGridViewCheckBoxCell) row.Cells[i]).Value = false;
                    }
                }
            }
            dataGridView1.Invalidate();
        }
    }
Run Code Online (Sandbox Code Playgroud)