Click here to Skip to main content
15,912,897 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to select the last row in DataGridView, when form loads the first time. So I wrote this code in Form_Load event :

C#
da.SelectCommand = new SqlCommand("SELECT * FROM Days", cn);

ds.Clear();
da.Fill(ds);

dataGridView1.DataSource = dsD.Tables[0];
dataGridView1.ClearSelection();
int nRowIndex = dataGridView1.Rows.Count - 1;
dataGridView1.Rows[nRowIndex].Selected = true;
dataGridView1.FirstDisplayedScrollingRowIndex = nRowIndex;
dataGridView1.Refresh();


But this isn´t doing anything. It still selects the first row, but this code works when I save the data in the database and then fill the dataset. But why not the first time when I load the form.
Posted
Updated 17-Nov-11 6:45am
v2

1 solution

Yes, the whole design of this control and documentation is a bit misleading. Try to set CurrentCell instead:

C#
dataGridView1.CurrentCell = dataGridView1.Rows[nRowIndex].Cells[0];


It will give you desired effect on selection, even if you use the selection mode to select entire row. The problem you faced was due to the fact that the cell is considered to be a real object of selection in all cases, not a row. To me, it looks like some API inconsistency. Anyway, try it.

By the way, don't use the names like dataGridView1, this is violation of Microsoft naming conventions. Yes, the name is created by Microsoft Designer, but who said you can keep this names? All members should be renamed semantically; re-factorization engine is your friend.

—SA
 
Share this answer
 
v3
Comments
tranesyasd 17-Nov-11 14:22pm    
it worked
thank you very much sir
Sergey Alexandrovich Kryukov 17-Nov-11 14:23pm    
Great! I knew it will help you.
You are very welcome.
Good luck, call again.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900