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;

}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM