使用這種方式始終綁定值有問題: 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;
}