简体   繁体   中英

How do I sort the Id in ascending order in datagridview

This is the code i used to sort the Id in ascending order.

SqlCeDataAdapter da = new SqlCeDataAdapter("select * from Contact_List order by Id ASC", con);
        DataTable dt = new DataTable();
        da.Fill(dt);
        dataGridView1.DataSource = dt;

It only sort the first digit of the number

for example i have Id : 1, 11, 2

and this code sort this list into = 1 , 11 , 2

but i want it to sort the list = 1 , 2 , 11

How to do it?

No it's not sorting by the first digit, it's sorting as if the values are text and not numbers. Text ordering is done lexicographically, so "11" comes before "2" just like "AA" comes before "B". I'm guessing your id column is a text value like VARCHAR ; it should really be a numeric value like INT if you're storing only numbers in it.

In the meantime, you should be able to get the correct behavior -- assuming you're only actually storing numeric values, by converting:

select * from Contact_List order by CONVERT(INT, Id) ASC

Either way, if you have any control over the database schema, you should let it do its job and store values with the proper data types.

I'm assuming you are using a varchar field for Id. Cast it as an int and then sort or change your data type in your table.

select CAST(Id AS int) from Contact_List order by CAST(Id AS int) ASC

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