Sort items in datatable

c#
10,512

Solution 1

Use a DataView:

DataTable dt; //comes from somewhere...
DataView dv = new DataView(dt)
dv.Sort = "Name ASC";
foreach(DataRowView drv in dv)
    //....

Solution 2

Method 1

    // orderby "FistName" column
    EnumerableRowCollection<DataRow> query = 
                    from order in datatable.AsEnumerable()
                    orderby datatable.Field<string>("FirstName")
                    select datatable;

    DataView view = query.AsDataView();

    // bind to your combobox
    combobox.DataSource = view;
    combobox.DataBind()

Method 2: if using DataSets

    DataTable datatable = dataSet.Tables["yourDataTable"];    
    DataView view = datatable .AsDataView();

    view.Sort = "FirstName desc, LastName desc";

    combobox.DataSource = view;
    combobox.DataBind();

Reference : Sorting with DataView (LINQ to DataSet)

Solution 3

Here's the answer that you're looking for.

DataTable MyDataTable;
const string SortByClause = "[SomeCol] ASC";
MyDataTable.DefaultView.Sort = SortByClause ;
Share:
10,512
num3ri
Author by

num3ri

Updated on June 16, 2022

Comments

  • num3ri
    num3ri over 1 year

    I have a datatable with one column that contain names.I want to load combobox with datatable such that names should be in alphabetic order for eg:first name starts with a. second name starts with b.How can i sort data in datatable.Can anybody help?

  • rlee923
    rlee923 almost 12 years
    very simple and such a nice solution.
  • TTT
    TTT about 11 years
    I think that should be DataRowView instead of DataRow: foreach(DataRowView dr in dv)