2012-10-10 33 views
0

我想對綁定到下拉列表的數據進行排序。Dropdown中的數據排序

我從數據庫中取出學生的名字,但認爲我不能直接使用orderby。

因爲我從數據庫中獲得的數據是Guid類型的學生ID。

然後我從ID找到全名。

下面的代碼

public DataTable GetAllStudentNameFromMentor(Guid MentorId) 
     { 
      DataTable AllStudents = new DataTable(); 
      AllStudents.Columns.Add("StudentID", typeof(Guid)); 
      AllStudents.Columns.Add("studentName", typeof(string)); 
      var allm = from sm in Db.StudentMentor 
         where sm.MentorID.Equals(MentorId) 
         select sm; 

      foreach (var v in allm) 
      { 
       string studentname = BussinesCollection.BussinesPerson.GetFullName(v.StudentID.Value); 
       AllStudents.Rows.Add(v.StudentID,studentname); 
      } 
      return AllStudents; 
     } 

我綁定表中的下拉列表。

ddlstudent.DataSource = m.bussinesCollection.BussinesMentor.GetAllStudentNameFromMentor(MentorID); 
     ddlstudent.DataBind(); 

但我想名字應該按字母順序。

會有人願意幫助我..

回答

0

我們可以通過下面的數據視圖排序數據表:

  1. 第一將數據錶轉換爲dataview,然後對

DataView dataView = new DataView(AllStudents);

dataView.Sort = "studentName ASC"; 
+0

它的工作完全適合我..謝謝了很多.. –

0

試試這個

public DetaView GetAllStudentNameFromMentor(Guid MentorId) 
{ 
    DataTable AllStudents = new DataTable(); 
    AllStudents.Columns.Add("StudentID", typeof(Guid)); 
    AllStudents.Columns.Add("studentName", typeof(string)); 
    var allm = from sm in Db.StudentMentor 
      where sm.MentorID.Equals(MentorId) 
      select sm; 
    foreach (var v in allm) 
    { 
     string studentname = BussinesCollection.BussinesPerson.GetFullName(v.StudentID.Value); 
     AllStudents.Rows.Add(v.StudentID,studentname); 
    } 
AllStudents.DefaultView.Sort = "studentName ASC"; 
return AllStudents.DefaultView; 
} 

如需更多關於這個Go here

+0

DafaultView需要哪個命名空間?因爲它顯示缺少命名空間的錯誤。 –

0

由於正在使用的ID和值對你可以使用一個字典,其可以很容易地順序。在將字典綁定到ddl之前,還要確保在標記或代碼後面更改ddl.DataValueField="Key"ddl.DataTextField="Value"

public Dictionary<Guid, string> GetAllStudentNameFromMentor(Guid MentorId) 
{ 
    Dictionary<Guid,string> myDic = new Dictionary<Guid,string>(); 

    var allm = from sm in Db.StudentMentor 
        where sm.MentorID.Equals(MentorId) 
        select sm; 

    foreach (var v in allm) 
    { 
      myDic.Add(v.StudentID, 
       BussinesCollection.BussinesPerson.GetFullName(v.StudentID.Value)); 
    } 

    return myDic.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value); 
}