System.InvalidCastException:'无法投射对象

时间:2019-02-15 13:07:05

标签: c# winforms

试图在组合框(下拉列表)中获取所选对象的值 出现此错误:

  

System.InvalidCastException:'无法转换类型为
的对象   'System.Collections.Generic.KeyValuePair`2 [System.String,schoolstuff.Employee]'   键入“ schoolstuff.Employee”。

我试图为cboEmployees.SelectedItem找到一个“值”,但似乎没有。。

employees[employee.Name] = employee;

cboEmployees.DataSource = new BindingSource(employees, null);
cboEmployees.DisplayMember = "Key";
cboEmployees.ValueMember = "Value";

private void cboEmployees_SelectedIndexChanged(object sender, EventArgs e)
{
    if (cboEmployees.SelectedItem == null) return;

    var employee = (Employee)cboEmployees.SelectedItem;

    if(employee != null)
        txtName.Text = employee.Name;
}

2 个答案:

答案 0 :(得分:1)

cboEmployees.SelectedItemKeyvaluePair<K,V>

所以您不能像这样投射它:(Employee)cboEmployees.SelectedItem

这应该起作用:

var employee = ((KeyValuePair<string,Employee>)cboEmployees.SelectedItem).Value;

或者您可以改用SelectedValue:

    if (cboEmployees.SelectedValue == null) return;
    var employee = (Employee)cboEmployees.SelectedValue;

答案 1 :(得分:1)

您的SelectedItem不是Employee

使用SelectedValue

var employee = (Employee)cboEmployees.SelectedValue;

或强制转换为KeyValuePair<string, Employee>

var kvp = (KeyValuePair<string, Employee>)cboEmployees.SelectedItem;
var employee = kvp.Value;