2

In my program (asp.net, C#) I am using a gridview to show data. it gets the data from the following query.

select * from Nametable where NameID in (4,3,1,22,15,8,9,5,7)

But the problem is Gridview is showing the data in ascending sort order of NameID like (1,3,4,5,7,8,9,15,22). I dont want data to be sorted, it should show exactly the way I mentioned in the query like (4,3,1,22,15,8,9,5,7)

Here is my code

private void loadGridView()
{
    Query = "select * from Nametable where NameID in (4,3,1,22,15,8,9,5,7)"

        DataSet ds = SqlHelper.ExecuteDataset(CommonSettings.Constring, CommandType.Text, Query);
        GridView1.DataSource = ds;
        GridView1.DataBind();
}
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
Henry
  • 847
  • 6
  • 24
  • 53

3 Answers3

5

That will be pretty difficult to do with the code that you've provided. It doesn't really have anything to do with your GridView, it's how the data is returned from SQL. SQL simply won't order the results for you that way. You'd have to specify an explicit CASE in an ORDER BY like this:

Query = "select * from Nametable where NameID in (4,3,1,22,15,8,9,5,7) " +
        "order by case NameID when 4 then 0 " +
                             "when 3 then 1 " +
                             "when 1 then 2 " +
                             "when 22 then 3 " +
                             "when 15 then 4 " +
                             "when 8 then 5 " +
                             "when 9 then 6 " +
                             "when 5 then 7 " +
                             "when 7 then 8 end";

Obviously this is very cumbersome. I strongly suggest you try sorting by a column instead.

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • You are correct. Its not the problem with Gridview. Its SQL server thats sorting it.Your suggestion of using case statement wont work for me as the order is dynamic. Thanks – Henry Apr 17 '13 at 21:19
0

Datagridview has a sort property for its columns. Probably sorting is enabled for the ID column. Check the properties of the datagridview to disable sorting or disable it programmatically

apomene
  • 14,282
  • 9
  • 46
  • 72
  • It's ASP.NET not Winforms. However, the `SortExpression` on a GridView column does not sort automatically but when the user clicks on the header of that column. – Tim Schmelter Apr 08 '13 at 21:27
0

You could create a temp table as a part of your query with the columns (NameId, SortOrder), join to it, and order the result set by SortOrder -- this would achieve what you are wanting to do -- but it's kinda hokey.

Cortright
  • 1,164
  • 6
  • 19