2012-10-10 32 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); 
}