Home > database >  If I have multiple datagridviews on one form, how would I allow a row selection to be active on only
If I have multiple datagridviews on one form, how would I allow a row selection to be active on only

Time:09-25

I have two datagridviews which display two seperate stored procedures at the same time, both on the same form. I have their "SelectionMode" properties set to "FullRowSelect".

However, I want only one row to be selectable at a time between the two dgvs. So if someone selects a row on dgv A, I want the selected row in dgv B to unhighlight or deactivate. And if someone selects a row in dgv B, I'd like the highlighted row in dgv A to unselect or deactivate. Is there a way to essentially share a

private void datagridview1_SelectionChanged(object sender, EventArgs e)

between two separate datagridviews? I'm not sure where to begin with this, so I have no code examples. Any assistance with this is appreciated. Thanks!!

CodePudding user response:

When selecting in dataGridView1, call dataGridView2.ClearSelection()

You mentioned a single event handler to handle both, which you can do. And you can write some code to find all other DataGridViews besides the one you clicked, and clear their selections.

private void dataGridView_SelectionChanged(object sender, EventArgs e)
{
    var s = (DataGridView)sender;
    if (s.SelectedRows.Count > 0)
    {
        var otherDataGridViews = this.Controls.OfType<DataGridView>().Except(new[] { s });
        foreach (var dgv in otherDataGridViews)
        {
            dgv.ClearSelection();
        }
    }
}

That will work if the DataGridViews are inside the same container i.e. same form, not in different Panels etc.

You must specify the same handler in the designer or designer code i.e.

// 
// dataGridView1
// 
...
this.dataGridView1.SelectionChanged  = new System.EventHandler(this.dataGridView_SelectionChanged);
// 
// dataGridView2
// 
...
this.dataGridView2.SelectionChanged  = new System.EventHandler(this.dataGridView_SelectionChanged);
  • Related