Link to home
Start Free TrialLog in
Avatar of Steven Xing
Steven XingFlag for Canada

asked on

Why order by does not work?

Visual studio 2010 C#   <----> SQL Server 2005
Programming a software to download and upload file to SQL server, I use a datagridview to show data. I add "order by" in SQL command as following code, but the data show on datagridview is still not ordered. Why?
ProductName is nvarchar in SQL database.


 

sc = new SqlConnection(strConn);
sc.Open();
string selectString = "select ProductName,Version,SubVersion,Filename,Description,Visible from VerControl order by ProductName desc";
sd = new SqlDataAdapter(selectString, strConn);
DataSet dSet = new DataSet();
sd.Fill(dSet, "VerControl");
dgwVerControl.DataSource = dSet.Tables["VerControl"].DefaultView;

Open in new window

Avatar of dsacker
dsacker
Flag of United States of America image

Run the query by itself in a SQL Server query window. Just for testing, add some additional fields into your ORDER BY statement. See if what is returned in your query in SQL Server and what comes back on your grid are the same. If not, you may have a property set on your grid column that is trumping your ORDER BY.
select ProductName,
       Version,
       SubVersion,
       Filename,
       Description,
       Visible
from	VerControl
order by ProductName desc,
         Version, SubVersion, Filename

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of JestersGrind
JestersGrind
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
give us an example of it not working , and the order you want to achieve.
Change the line no 7 code from
dgwVerControl.DataSource = dSet.Tables["VerControl"].DefaultView;

Open in new window

To
dgwVerControl.DataSource = dSet.Tables["VerControl";

Open in new window

Query produces "result SET". By definition SET does not have the ORDER.
For sure some assumptions are used by default like ORDER BY ROW_NUMBER in the SET.

But to have what you need you must specify it in the GridView.

I think that users require the functionality "Click the Header to Sort".

Whatever you will specify is the "default (initial) sort for users".
there is no problem with your query here. you need to control the datagrid property.I think smartcheater\jestersgrind idea will work .