完整的异常消息:
System.InvalidCastException
HResult=0x80004002
Message=Unable to cast object of type 'System.String' to type 'MyListBoxItem'.
Source=Image Crop
StackTrace:
at Image_Crop.Form1.listBox1_SelectedIndexChanged(Object sender, EventArgs e) in D:\Csharp Projects\Image Crop\Form1.cs:line 387
at System.EventHandler.Invoke(Object sender, EventArgs e)
at System.Windows.Forms.ListBox.OnSelectedIndexChanged(EventArgs e)
at System.Windows.Forms.ListBox.set_SelectedIndex(Int32 value)
at System.Windows.Forms.ListBox.RefreshItems()
at System.Windows.Forms.ListBox.OnDisplayMemberChanged(EventArgs e)
at System.Windows.Forms.ListControl.SetDataConnection(Object newDataSource, BindingMemberInfo newDisplayMember, Boolean force)
at System.Windows.Forms.ListControl.set_DisplayMember(String value)
字符串形式的项目内容屏幕截图:
exception message
这是一个项目对象的屏幕截图。我怎样才能访问消息?
item object
代码:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var item = ((ListBox)sender).SelectedItem;
MyListBoxItem mm = (MyListBoxItem)item;
var val = mm.Message;
int index = val.LastIndexOf(",");
string you = val.Substring(index + 1);
if (File.Exists(you))
{
pictureBox1.Image = System.Drawing.Image.FromFile(you);
}
}
异常消息错误位于以下行:
MyListBoxItem mm = (MyListBoxItem)item;
我试着把它转换成字符串,但没有用。
这是表单1中的MyListBoxItem类:
public class MyListBoxItem
{
public Color ItemColor { get; set; }
public string Message { get; set; }
}
1条答案
按热度按时间rwqw0loc1#
根据您的代码,
ListBox.SelectedItem
似乎是String
对象。强制转换仅适用于相似类型(如Collection/List、int/long、char/byte等)。您不能将字符串强制转换为对象,因为C#运行时和编译器不了解如何反序列化字符串并生成对象。您需要添加一个可以从字符串构造
MyListBoxItem
对象的方法。C#中的命名约定是:MyListBoxItem.Parse
.