user42348
user42348

Reputation: 4319

Sort items in datatable

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?

Upvotes: 6

Views: 11431

Answers (5)

Seva Alekseyev
Seva Alekseyev

Reputation: 61396

Use a DataView:

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

Upvotes: 15

Cedric Michel
Cedric Michel

Reputation: 520

use an typed dataset create a datatable in precising type of data for example i have create a dsAppointment

 DsAppointment dsAppointmentTmp = new DsAppointment();
 DsAppointment dsAppointment = new DsAppointment();
//add all appointment
 dsAppointmentTmp.Appointment.AddAppointmentRow(name,start,end,body)
//use select(filter,sort(name of columns)
DataRow[] rows1 = dsAppointmentTmp.Tables[0].Select(string.Empty, dsAppointmentTmp.Tables[0].Columns[1].ToString());

            foreach (DataRow thisRow in rows1)
            {
                    dsAppointment.Tables[0].Rows.Add(thisRow.ItemArray);

            }

//return dsAppointment sorted return dsAppointment;

Upvotes: 0

bitcycle
bitcycle

Reputation: 7812

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

DataTable MyDataTable;
const string SortByClause = "[SomeCol] ASC";
MyDataTable.DefaultView.Sort = SortByClause ;

Upvotes: 3

Asad
Asad

Reputation: 21938

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)

Upvotes: 4

Related Questions