11

I have some numeric codes stored in a DataTable. When I try to sort it using DataView it sorts the column by string. What is the easiest way to sort the data as integer/number?

DataView view = dt.DefaultView();
view.Sort = "Code asc";
dt = view.ToTable();

Data in datatable: 128, 123, 112, 12, 126

after sort it shows: 112, 12, 123, 126, 128

expected result: 12, 112, 123, 126, 128

4 Answers 4

13

Here is working example. You can create another DataTable via Clone, and change the data type of the column to Int and copy the data.

    DataTable dt = GetTable(); // Assume this method returns the datatable from service      
    DataTable dt2 = dt.Clone();
    dt2.Columns["Code"].DataType = Type.GetType("System.Int32");

    foreach (DataRow dr in dt.Rows)
    {
        dt2.ImportRow(dr);
    }
    dt2.AcceptChanges();
    DataView dv = dt2.DefaultView;
    dv.Sort = "Code ASC";
Sign up to request clarification or add additional context in comments.

1 Comment

what will happen if code is "001", will datatype changing from string to integer omit the leading zeros?
5

One option is to add a Calculated column with the right type and sort on it.

Like this:

dt.Columns.Add( "Int32_Code", typeof( int ), "Code" );
dt.DefaultView.Sort("Int32_Code");
dt = dt.DefaultView.ToTable();

Comments

2

When you are creating a column in data table, define it as typeof(int)

dt.Columns.Add("Code", typeof(int));

2 Comments

Hmm, in my code I am calling the webservice that returns me the datatable and I simply do DataTable dt = soaRequest.GetMasterList();.
try this dt.Columns["Code"].DataType = Type.GetType("System.Int32");
0

create a new column in datatable as given below and sort on new column code_int Dt.Columns.Add("Code_int", typeof(Int16), "Convert(Code, 'System.String')");

1 Comment

Welcome to Stack Overflow! Please consider reading other people's answers, before posting your own. Your answer has been mentioned here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.