我有一个下拉列表如下:
DropDownList1.DataSource = Students.GetStudents();
DropDownList1.DataBind();
-----------
我有一个DataAccess类,如下所示:
public IEnumerable<StudentEntity> GetStudents()
{
List<StudentsEntity> studentsList = new List<StudentsEntity>();
studentsList = Service.GetList() // some service getting a list of sutdents
return new BindingList<StudentEntity>(studentsList);
}
我有一个DataObject类,如下所示:
public class StudentEntity : IComparable
{
public string fullname { get {return firstName +", "+ lastName;}
public string ID {get; set;}
public string Height {get; set;}
public string Firstname {get; set;}
public string Lastname {get; set;}
public int CompareTo(object obj)
{
StudentEntity entity = (StudentEntity) obj;
return Lastname.CompareTo(entity.Lastname);
}
}
在UI级别 - 下拉列表中会显示“学生全名”,那么如何从DropDown列表中获取所选学生的“ID”?
答案 0 :(得分:1)
从DropDownList中获取所选项目并将其强制转换为StudentEntity类型的对象。之后,您可以获取该对象的ID。伪代码:
var selectedItem = myDropDown.SelectedItem as StudentEntity;
var ID = selectedItem.ID;
修改强>
'hvd'正确地评论了我。由于这是在webcontext中,你必须实现这一点有点不同。您可以设置DropDownList的DataTextField和DataValueField。将ID绑定到DataValueField,当您获得SelectedItem时,获取Value-property并获得ID。
var selectedItem = myDropDown.SelectedItem;
var ID = selectedItem.Value;
答案 1 :(得分:0)
在事件处理程序中:
var id = ((StudentEntity)sender).Id;