Getting exception System.InvalidCastException: 'Unable to cast object of type 'System.String' to type 'MyListBoxItem'.' how to handle it?
The full exception message:
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)
Screenshot of the item content as string:
and this is a screenshot of the item object. how do I get access to the Message?
The code:
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);
}
}
The exception message error is on the line:
MyListBoxItem mm = (MyListBoxItem)item;
This is the MyListBoxItem class in Form1:
public class MyListBoxItem
{
public Color ItemColor { get; set; }
public string Message { get; set; }
}