0

I have a listbox with one item on it, it can then get replaced by several items (words) taken from the text inputted in a textbox. They're added with listbox.Items.Add(word). I want to be able to convert those words from the listbox back into strings as they are selected (so I can do other stuff with them) but I have encountered two problems that I'm not sure how to deal with:

  1. When the original item is selected I get an exception:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

when using string s = ((ListBoxItem)listbox.SelectedItem).Content.ToString();

and

"System.NullReferenceException: 'Object reference not set to an instance of an object.'

System.Windows.Controls.Primitives.Selector.SelectedValue.get returned null."

when using string s = listbox.SelectedValue.ToString();

  1. When any of the new items are selected nothing happens. I assume this is because the event handler is only attached to the single item that's on the list in the beginning, but I am not sure how to apply it to items that aren't there yet. Is there an event handler for when any item from a listbox is selected?

Any help would be appreciated, thank you in advance.

Clemens
  • 123,504
  • 12
  • 155
  • 268
Rhyme
  • 121
  • 7
  • 1
    `I assume this is because the event handler is only attached to the single item that's on the list in the beginning` - are you using listbox `SelectionChanged` event? Then that would not be the case. – Longoon12000 Nov 27 '19 at 16:42
  • Using it did solve both problems, thank you! – Rhyme Nov 27 '19 at 17:28

2 Answers2

1

You can try this, you can test the selection of an element in your listbox :

 private void youListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
 {
     if(yourListBox.SelectedItem != null)
     {
        ....
     }
 }
Alexus
  • 276
  • 1
  • 5
  • 22
1

You should listen to the SelectionChanged event. See below

        public MainWindow()
        {
            InitializeComponent();

            ListBox.Items.Add("Word1");
            ListBox.Items.Add("Word2");
            ListBox.Items.Add("Word3");
            ListBox.Items.Add("Word4");

            ListBox.SelectionChanged += ListBox_SelectionChanged;
        }

        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var listBoxValue = ListBox.SelectedValue.ToString();
            Console.WriteLine(listBoxValue);
        }
Tommehh
  • 872
  • 1
  • 17
  • 44
  • 2
    even easier. SelectionChangedEventArgs store a lot of properties that let you don't need to call listbox reference. – DrkDeveloper Nov 27 '19 at 17:23
  • I could only select one answer and the other one included code that deals with no selection (which as it turned out I needed as well), but this answer was a great help too, thanks! – Rhyme Nov 27 '19 at 17:31