How to get selected item from ListBox

I am struggling to find a way to get the selected item from a ListBox. The following gives a syntax error and using ToString() just returns the name of the damn thing. The list box was populated with strings.

string selected = myList.SelectedItem; but SelectedItem is a ListBoxItem.

It looks like my only option is to keep a separate list that matches with the listbox entries and use the SelectedIndex to point to the one I want in my separate list.

Why don’t you inherit from ListBoxItem and implement the
implicit operator string.
Something like this:

public class MyListBoxItem : ListBoxItem
{
    private readonly string _value;
    public MyListBoxItem(string                          value) { this._value = value; }
    public static implicit operator string(MyListBoxItem item) => item._value;
    public override                 string ToString()          => this._value;
}

using:

ListBox box = new ListBox();
box.Items.Add(new MyListBoxItem("str1"));
box.Items.Add(new MyListBoxItem("str2"));
box.Items.Add(new MyListBoxItem("str3"));
box.Items.Add(new MyListBoxItem("str4"));
box.Items.Add(new MyListBoxItem("str5"));

box.SelectedIndex = 0;
string s0 = box.SelectedItem.ToString();      // call ToString()
box.SelectedIndex = 3;
string s1 = (MyListBoxItem)box.SelectedItem;  // call implicit conversion
Debug.WriteLine(s0);
Debug.WriteLine(s1);
3 Likes