Getting exception System.InvalidCastException: 'Unable to cast object of type 'System.String' to type 'MyListBoxItem'.' how to handle it?

sharon glipman 441 Reputation points
2023-02-24T18:19:41.9133333+00:00

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:

the item string content

and this is a screenshot of the item object. how do I get access to the Message?

Message item

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; }
    }
Developer technologies | Windows Forms
Developer technologies | C#
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.