C# ComboBox绑定值问题

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

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;

}

posted @ 2019-03-05 10:57  杨jian  阅读(1804)  评论(3编辑  收藏  举报