Chad
Chad

Reputation: 24689

WinForm ComboBox SelectedValue property vs SelectedIndex

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?

Upvotes: 2

Views: 2106

Answers (1)

Kailash Chandra Polai
Kailash Chandra Polai

Reputation: 241

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";

Upvotes: 0

Related Questions