gpt4 book ai didi

c# - 从下拉列表中获取 IEnumerable 的选定值

转载 作者:太空宇宙 更新时间:2023-11-03 13:53:49 27 4
gpt4 key购买 nike

我有一个下拉列表如下:

DropDownList1.DataSource = Students.GetStudents();
DropDownList1.DataBind();
-----------

我有一个如下的数据访问类:

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 级别 - “学生全名”显示在下拉列表中,那么如何从下拉列表中获取所选学生的“ID”?

最佳答案

从 DropDownList 中获取所选项目并将其转换为 StudentEntity 类型的对象。之后您可以获得该对象的 ID。伪代码:

var selectedItem = myDropDown.SelectedItem as StudentEntity;
var ID = selectedItem.ID;

编辑:

'hvd' 正确地评论了我。由于这是在网络上下文中,因此您必须以不同的方式实现这一点。您可以设置 DropDownList 的 DataTextField 和 DataValueField。将 ID 绑定(bind)到 DataValueField,当您获取 SelectedItem 时,获取 Value-property 并获得 ID。

var selectedItem = myDropDown.SelectedItem;
var ID = selectedItem.Value;

关于c# - 从下拉列表中获取 IEnumerable<T> 的选定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12936512/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com