Initializing DataGridView selection


Duy Lam

I've created a windows Form that contains a TabControl. In the SECOND
tab of the tab control, I have a DataGridView control. The grid view
is initialized with some data in the form's constructor and I want to
have a specific row selected in the grid view upon startup. However, I
can't seem to get the row to be selected -- when I switch to the tab,
it loads up with the first row selected automatically. How can I get
this to work?

To test this, I created a Windows Forms App and added a DataGridView
to form. In the form constructor I have the following code:

public Form1()

gridview.Columns.Add(new DataGridViewTextBoxColumn());
gridview.Rows[1].Selected = true;

.....I would expect the "2" to be selected when the dialog appears and
I go to the tab, but instead the "1" is selected.

To look into it, I handled the gridview's SelectionChanged event like

private void OnSelectionChanged(object sender, EventArgs e)
if (gridview.SelectedRows.Count > 0)
int selectedRow = gridview.SelectedRows[0].Index;
MessageBox.Show("Row selected: " + selectedRow);
else MessageBox.Show("No row selected.");

When I run, I initially get a messagebox that says "Row Selected:
1" (which is raised by my code in the constructor, which is correct).
However, when I switch to the second tab (which contains the grid
view), I get a messagebox saying "No row selected.". I traced into it
and looked at the call stack and some framework/external code raises
the "no rows selected" SelectionChanged event (but it's framework/
external code, so I don't know where exactly this is happening). I'm
not too familiar with .NET's inner workings but I guessed that when
the second tab is shown for the first time, the grid view
reinitializes itself in some fashion. However, I simply don't know
where else I can initialize the selection besides the constructor.

How can I get this to work right? Is there some better place for me to
set the grid view selection? I tried handling the tab control's
Selected event and setting the grid view selection there, but that
didn't really work either.


Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question