David Mordigal
David Mordigal

Reputation: 409

DataGridView not selecting last row on load

I have a DataGridView as part of a form that, when all of its rows are populated, should select the last row by default.

public MyForm()
{
    InitializeComponent();
    Reload();
}

private void Reload()
{
    // add/populate the rows here

    if(dgv.Rows.Count > 0)
    {
        dgv.Rows[dgv.Rows.Count - 1].Selected = true;
    }
}

I have the SelectionMode set to FullRowSelect and MultiSelect is false.

Anyone know why this isn't working? The first row is always still selected when the form pops up.

Upvotes: 0

Views: 87

Answers (1)

Darren H
Darren H

Reputation: 460

This issue stems from the Order of Events in Windows Forms when loading a Form. If you call Reload() in the constructor of the Form the forms controls haven't actually had a chance to load yet. Instances of them exist, but not the rendered objects.

Instead you should override one of the other form load events such as OnLoad and call Reload() from there. Remove the call to Reload() from your constructor.

public MyForm()
{
    InitializeComponent();
}

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    Reload();
}

private void Reload()
{
    // add/populate the rows here
    if(dgv.Rows.Count > 0)
    {
        dgv.Rows[dgv.Rows.Count - 1].Selected = true;
    }
}

Using this method will ensure that your controls have finished loading before you start manipulating them.

Upvotes: 1

Related Questions