为什么我得到这个错误窗口形式?

时间:2016-05-12 01:39:29

标签: c# exception

System.InvalidCastException: Unable to cast object of type 'System.String' to type 'Cookie.Dozen'.  at Cookie.CookieSource.listBox1_SelectedIndexChanged(Object sender,  EventArgs e) in Form1.cs:line 112

第112行如下:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    this.dozen = (Dozen) this.listBox1.SelectedItem;
    this.CostChosenLb.ResetText();
}

我要做的是,当我从列表框中选择一个项目时,它将在文本框中显示价格。但每当我尝试这样做时,我都会遇到错误。救命啊!

1 个答案:

答案 0 :(得分:0)

您的ListBox绑定到字符串Type而不是Dobu类型。您应该检查如何设置ListBox Items属性。

this.listBox1.Items = yoursList

您可以尝试将代码更改为:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    this.dozen = this.listBox1.SelectedItem as Dozen;
    this.CostChosenLb.ResetText();
}