欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# ComboBox绑定值问题

程序员文章站 2022-03-20 10:21:20
使用这种方式始终绑定值有问题: cbxSchool.DataSource = schoolList; cbxSchool.DisplayMember = "school_name"; cbxSchool.ValueMember = "school_id"; 选择改变事件获取选中值:cbxSchool ......

使用这种方式始终绑定值有问题:

cbxschool.datasource = schoollist;
cbxschool.displaymember = "school_name";
cbxschool.valuemember = "school_id";

选择改变事件获取选中值:cbxschool.selectedvalue 始终是对象,不是想要的id。

解决方法:

if (schoollist != null && schoollist.count > 0)
{
cbxschool.items.clear();
for (int i = 0; i < schoollist.count; i++)
{
cbxschool.items.add(schoollist[i].school_name);
}

//选择默认值

int selectindex = schoollist.findindex(a => a.school_id == schoolid);
cbxschool.selectedindex = selectindex == -1 ? 0 : selectindex;

//获取选中值

  string  schoolname = schoollist[cbxschool.selectedindex].school_name;

}