-1
comboBox.Items.AddRange(Enumerable.Range(18, 38).Cast<object>().ToArray());
comboBox.SelectedIndex = 0;
Console.WriteLine(comboBox.SelectedValue + "test");

I get just "test" without the "18" printed. I also don't clearly understand what's the difference between SelectedValue and SelectedItem, even if I read the guide.

Bersekz
  • 29
  • 6
  • Does [this question](https://stackoverflow.com/questions/4902039/difference-between-selecteditem-selectedvalue-and-selectedvaluepath) not help? `SelectedValue` relies on `SelectedValuePath`. It seems you want `SelectedItem` here. – Charles Mager Jan 08 '18 at 17:26
  • 2
    The WPF combobox's Items collection doesn't have an AddRange() method. Is this really winforms, not WPF? In winforms, `ComboBox.Items` has an `AddRange(object[] items)` method. – 15ee8f99-57ff-4f92-890c-b56153 Jan 08 '18 at 17:28

1 Answers1

1

In Winforms, you need to set the ValueMember property of the ComboBox to make SelectedValue work. If you populated your combo box with a User class that has Name and ID properties, you could set DisplayMember to "Name" and ValueMember to "ID", and then the SelectedValue would be the ID value of the selected User object. In that case, SelectedItem would be the whole User object the user selected. You'd have to cast it, of course: User user = comboBox2.SelectedItem as User;.

If ValueMember is null or "", SelectedValue will always just be null. That's what you're seeing.

You're populating your combo box with integers, which have no value property. They are the value. So what you want is SelectedItem, which gives you the whole object the user selected (an integer is an object, in its own humble way):

comboBox.Items.AddRange(Enumerable.Range(18, 38).Cast<object>().ToArray());
comboBox.SelectedIndex = 0;
Console.WriteLine(comboBox.SelectedItem + "test");

This question was tagged as WPF, but I don't believe that's really the case. In WPF ComboBox.Items has no AddRange() method. In winforms, however, it does, and the type of its parameter is object[]. So in winforms, your code compiles, and the .Cast<object>().ToArray() part makes sense. My belief is that you're using winforms.

Alternatively, it may be that you've managed to create an instance of System.Windows.Forms.ComboBox in a WPF project. If that's the case, I would recommend using the WPF combobox control instead.