VAAA
VAAA

Reputation: 15039

C# DataGridView how to programatically fire the selected event

I have a DataGridView in a form and I have the following code:

 //Scroll to the last row
            gridStore.FirstDisplayedScrollingRowIndex = gridStore.RowCount - 1;
            // select new row
            gridStore.Rows[gridStore.Rows.Count - 1].Selected = true;

I realize that .Selected doenst fire the SelectionChange event:

 private void gridStore_SelectionChanged(object sender, EventArgs e)
        {

        }

And I need to fire that event when the row is selected programatically.

Any clue?

Upvotes: 1

Views: 4971

Answers (1)

Hari Prasad
Hari Prasad

Reputation: 16956

As you rightly figured out, when the SelectMode set to FullRowSelect SelectionChanged event will not fire.

You have two workarounds to fix this issue.

Option 1

Separate the logic you would like to perform in common between gridStore_SelectionChanged and when you update the selection explicitly and call that method in both events.

private void DoSomething()
{

}

private void gridStore_SelectionChanged(object sender, EventArgs e)
{
     ...
     DoSomething();
}

and

gridStore.FirstDisplayedScrollingRowIndex = gridStore.RowCount - 1;
// select new row
gridStore.Rows[gridStore.Rows.Count - 1].Selected = true;

DoSomething();

Option 2:

Explicitly you trigger the event after making the selection (not preferable way, but works).

gridStore.FirstDisplayedScrollingRowIndex = gridStore.RowCount - 1;
// select new row
gridStore.Rows[gridStore.Rows.Count - 1].Selected = true;
gridStore_SelectionChanged(this, new EventArgs())

Upvotes: 1

Related Questions