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

Hello @Dave_McLaughlin,
To get the selected string from a ListBox populated with strings, use:

string selected = myListBox.SelectedItem.ToString();

If you’re seeing System.Windows.Controls.ListBoxItem, try:

string selected = ((ListBoxItem)myListBox.SelectedItem).Content.ToString();

This extracts the actual string content from the selected item.

Best Regards,
James Henry

Dear James,

I just wanted to take a moment to thank you for your enlightening contribution to the forum. Your insights were both thought-provoking and informative. The clarity and depth with which you shared your thoughts truly made a difference, and I’m sure many, including myself, will carry your advice forward.

Looking forward to reading more of your contributions in the future!

1 Like