简体   繁体   中英

How to preserve order in Gridview

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();
}

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.

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

您可以使用列(NameId,SortOrder)创建一个临时表作为查询的一部分,将其联接起来,然后按SortOrder对结果集进行排序-这将实现您想要的功能-但这有点白费力气。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM