1

I have a DataTable which has 10 columns, I would like to sort the table by a column index 10 from largest to smallest. I know this should be easy for some but this is my first time using such a DataTable

all the website that i have found all say that you have to know the column name but i dont have that and would like to make reference to the column by the index value of the column. which should sort all the rows in that datatble

5
  • What problem(s) do you have exactly? What have you tried so far and failed? Commented Dec 7, 2012 at 11:25
  • Which ever sit that i have found always just reference to the column name and the data does not sort itself. Commented Dec 7, 2012 at 11:28
  • Try DataTable dt = new DataTable(); //Then fill values DataView dv = dt.AsDataView(); dv.Sort = dv.Table.Columns[index].ColumnName + " DESC"; Commented Dec 7, 2012 at 11:29
  • post your code so we can see what you have tried Commented Dec 7, 2012 at 11:30
  • will this sort the data for the one time or would it keep the sorted data in the same datatable Commented Dec 7, 2012 at 11:33

2 Answers 2

2

You can use the DefaultView and the ColumnName to sort.

dataTable.DefaultView.Sort = dataTable.Columns[9].ColumnName + " DESC";

Working example:

    DataTable dt = new DataTable();
    //Define columns to DataTable 
    dt.Columns.Add("Id");
    dt.Columns.Add("Name");


    //Adding rows to DataTable 
    DataRow row1 = dt.NewRow();
    row1["ID"] = 1;
    row1["Name"] = "Jack";
    dt.Rows.Add(row1);


    DataRow row2 = dt.NewRow();
    row2["ID"] = 2;
    row2["Name"] = "Fruit";
    dt.Rows.Add(row2);

    DataRow row3 = dt.NewRow();
    row3["ID"] = 3;
    row3["Name"] = "Ball";
    dt.Rows.Add(row3);

    dt.DefaultView.Sort = dt.Columns[1].ColumnName + " ASC";

    foreach (DataRowView drv in dt.DefaultView)
    {
        for (int i = 0; i < dt.Columns.Count; i++)
            Console.WriteLine(drv[i]);
    }
Sign up to request clarification or add additional context in comments.

2 Comments

will this order the rows of data
it sorts the rows in the DefaultView
1

Try

DataTable dt = new DataTable(); 
//Then fill values 
DataView dv = dt.AsDataView(); // DataView dv = dt.DefaultView();
dv.Sort = dv.Table.Columns[index].ColumnName + " DESC";
dt = dv.Table;

3 Comments

Error Message Can not find column
@JimBrad Instead of DataView dv = dt.AsDataView(); try DataView dv = new DataView(); dv = dt.DefaultView();
now it runs the program without any issues but yet it still doesnt sort the data

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.