2
votes

I'm adding an "Index" object to each item in a Comboxbox

foreach (var index in indexes) { UniqueIndexComboBox.Items.Add(index); }

When the user selects one of the index items from the drop, the following events are both fired. I'm not sure the difference.

private void UniqueIndexComboBox_SelectedValueChanged(object sender, EventArgs e) private void UniqueIndexComboBox_SelectedIndexChanged(object sender, EventArgs e)

When I interegate the following properties, the SelectedValue is always null but I can still access the selected Index value by using the SelectedIndex value as an index into the items list.

Using a WinForm ComboBox, why would the Selected ? UniqueIndexComboBox.Items[UniqueIndexComboBox.SelectedIndex] == null false ? UniqueIndexComboBox.SelectedValue == null true

Why doesn't the SelectedValue option also work? Is the value of the DropDownStyle property relevant?

1
SelectedValue requires ValueMember property and populating ComboBox with loop won't set ValueMember, you need to give indexes as datasource. - Berkay
As Berkay said, the SelectedIndex property is the zero-based index of the currently selected item in the items list or -1 if no item is selected. It is not required to add a (database-inspired?) index to the values. See the MSDN documentation for further details. If SelectedIndex is >= 0, UniqueIndexComboBox.Items[UniqueIndexComboBox.SelectedIndex] is always non-null, because an item IS selected. SelectedValue is used if the 'ComboBox' is data-bound. - KBO

1 Answers

0
votes

SelectedIndex is the Zero based index number (indirectly place number) SelectedValue is the actual value of the selected item (which is invisible to user). in your case SelectedValue is always null as you have not supplied it as below.

to achieve ComboBox's SelectedValue, the combobox should be set it's DataSource Property not Items.Add() method

for example

        var items = new List<object>();
        for (int i = 1; i <= 10; i++)
        {
            items.Add(new { Value = i, Text = "Text "+i });
        }

        comboBox1.DataSource = items;
        comboBox1.DisplayMember = "Text";
        comboBox1.ValueMember = "Value";