thevan
thevan

Reputation: 10354

Sorting the DataTable is not working

I have one DataTable called "DTStage". It has two columns such as "SeqNbr" and "StageID".

I want to sort the datatable based on "SeqNbr".

The DataTable has the following records:

     SeqNbr         StageID
    --------      -----------
       0               1
       1               2
       2               3
       3               4
       4               5
       5               6
       6               7
       7               8
       8               9
       9               10
       10              11
       11              12
       12              13
       13              14
       14              15
       15              16
       16              17
       18              18
       17              19

I have used two methods to sort this datatable, they are as follows:

 DTStage = new DataView(DTStage, "", "SeqNbr asc", DataViewRowState.CurrentRows).ToTable();

                     &

 DataView dv = DTStage.DefaultView;
 dv.Sort = DTStage.Columns["SeqNbr"] + " asc";
 DTStage = dv.ToTable();

But both gives the same result as follows:

     SeqNbr         StageID
    --------      -----------
        0               1
        1               2
       10               11
       11               12
       12               13
       13               14
       14               15
       15               16
       16               17
       17               19
       18               18
        2               3
        3               4
        4               5
        5               6
        6               7
        7               8
        8               9
        9               10

Why this is not working properly? How to solve this problem?

Upvotes: 1

Views: 5312

Answers (5)

getedoi
getedoi

Reputation: 1

It looks like it's comparing strings. Try converting them to int.

Upvotes: 0

antew
antew

Reputation: 979

You should delcare your datatable as

Datatable DTStage = new Datatable();

DTStage.Columns.Add("SeqNbr", typeof(int));

Cheers

Upvotes: 0

Grzegorz Kaczan
Grzegorz Kaczan

Reputation: 21676

Its a natural sorting(string compare). You need to tell dataTable that those are integers.

Upvotes: 2

HatSoft
HatSoft

Reputation: 11201

Instead of DTStage = dv.ToTable(); please use DTStage = dv.Table;

else you will need make the column your sorting as number type on your Sql Table

Upvotes: 1

Davide Piras
Davide Piras

Reputation: 44605

it looks like your SeqNbr column is of type string so it gets sorted by characters and not as numbers. if those are numbers (I assume integers) why don't you have the column type as int in the DataTable?

This should help you: Sort string items in a datatable as int using c#

Upvotes: 4

Related Questions