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

前端 未结 4 1346
后悔当初
后悔当初 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:10

    Thanks to KeithS for the helpful answer.

    When I looked in the doc for CellValueChanged, I found this helpful bit:

    The DataGridView.CellValueChanged event occurs when the user-specified value is committed, which typically occurs when focus leaves the cell.

    In the case of check box cells, however, you will typically want to handle the change immediately. To commit the change when the cell is clicked, you must handle the DataGridView.CurrentCellDirtyStateChanged event. In the handler, if the current cell is a check box cell, call the DataGridView.CommitEdit method and pass in the Commit value.

    This is the code I used to get the radio behavior:

        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();
            }
        }
    

提交回复
热议问题