comecme
comecme

Reputation: 6386

Why does deselecting specific DataGridViewRow also deselect all other rows?

I've got a Form with a DataGridView. Based on certain conditions, I programmatically deselect a single Row (by setting Selected to false). But when I do that, if another row was currently selected it is deselected also. I've set the DataGridView to MultiSelect = false. The user should only be able to select a single row.

It seems that setting any row's Selected property causes the control to see that as selecting the row, thereby deselecting any previously selected row. The fact that I'm setting the Selected property to false doesn't change that behavior. This only happens if MultiSelect is set to false and SelectionMode is set to FullRowSelect though.

I can solve it by only setting the property if it's currently true.

if (row.Selected) row.Selected = false;

But I'd like to know why this happens. And why only when SelectionMode is set to FullRowSelect?

Complete example

The following sample code contains a complete working example. The constructor will add three rows. Clicking the button will deselect the middle row. But no matter which row was selected before clicking the button, the end result will be that no row is selected.

using System;
using System.Windows.Forms;

class MainForm : Form
{
    static void Main() { Application.Run(new MainForm()); }

    private DataGridView _dataGridView;
    private Button _SelectButton;

    public MainForm()
    {
        _dataGridView = new DataGridView
        { ReadOnly = true, AllowUserToAddRows = false };
        _dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
        _dataGridView.Dock = DockStyle.Fill;
        _dataGridView.MultiSelect = false;
        _dataGridView.Columns.Add(new DataGridViewColumn
        { CellTemplate = new DataGridViewTextBoxCell() });
        _dataGridView.Rows.Add("1");
        _dataGridView.Rows.Add("2");
        _dataGridView.Rows.Add("3");
        Controls.Add(_dataGridView);
        _SelectButton = new Button { Text = "Deselect middle row" };
        _SelectButton.Click += _SelectButton_Click;
        _SelectButton.Dock = DockStyle.Bottom;
        Controls.Add(_SelectButton);
    }

    void _SelectButton_Click(object sender, EventArgs e)
    {
        _dataGridView.Rows[1].Selected = false;
    }
}

Upvotes: 0

Views: 358

Answers (1)

Geo242
Geo242

Reputation: 597

I agree this is odd behavior. If you allow multi select, it works as expected, but when you don't allow multi select it seems to operate as if you called _dataGridView.ClearSelection;. The only solution I can see is to simply test if the row in question is selected before deselecting it.

void _SelectButton_Click(object sender, EventArgs e)
{
    if (_dataGridView.Rows[1].Selected)
    {
        _dataGridView.Rows[1].Selected = false;
    }            
}

Upvotes: 0

Related Questions