我正在使用 winform 并使用组合框。
我按此顺序设置组合框的属性
combobox.DisplayMember
combobox.ValueMember
combobox.DataSource
绑定代码是
private void BindBranch()
{
BranchClass branch = new BranchClass();
branch.Active = true;
branch.Company = Startup.CompID;
if (branch.GetAll(out dtBranch, out result))
{
cmbBranch.DisplayMember = "br_name";
cmbBranch.ValueMember = "br_id";
cmbBranch.DataSource = dtBranch;
}
else
{
MessageBox.Show(result);
}
}
我在我的应用程序中多次使用组合框,我不知道我在哪里犯了错误
SelectedItem 属性有时会根据“ValueMember”属性的数据类型返回精确值(int,string),但有时它会返回“DataRowView”,在这种情况下会引发 InvalidCastException。
我读过这是因为在组合框中设置属性的顺序。但现在情况并非如此。
绑定代码是
调用代码是
private void BindEmployee()
{
employee.Branch = Convert.ToInt32(cmbBranch.SelectedItem); // InvalidCastException thrown here
employee.Active = true;
var dt = new DataTable();
if (employee.GetEmployee(out dt, out result, false))
{
cmbEmployee.DisplayMember = "emp_name";
cmbEmployee.ValueMember = "emp_id";
cmbEmployee.DataSource = dt;
}
}