2010-02-19 22 views
4

我有一個數據表,其中一列包含names.I想要使用數據表加載組合框,使得名稱應該按字母順序排列,例如:名字以a開頭。 第二個名字以b開頭。我可以如何對datatable中的數據進行排序。任何人都可以幫忙嗎?對數據表中的項目進行排序

回答

13

使用一個DataView:

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

非常簡單,這樣一個不錯的解決方案。 – rlee923 2012-01-04 09:44:42

+0

我認爲這應該是DataRowView而不是DataRow: foreach(DataRowView dr in dv) – TTT 2012-10-17 22:34:34

4

方法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() 

方法2:如果使用數據集

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

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

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

參考:Sorting with DataView (LINQ to DataSet)

3

Here's the answer你在找。

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

使用類型數據集 創建在precising類型例如數據 的數據表中我有創建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); 

      } 

//返回dsAppointment排序 返回dsAppointment;

相關問題