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