Rivasa
Rivasa

Reputation: 6740

Textbox not displaying value after selecting from ComboBox Dropdown

so I have a Combo Box and I have a list made using a KeyValuePair<int, decimal>. I want the textbox I have selected to show the value according to the key when I select it from drop-down textbox.

Relevant code:

// Make a list of truck weight and MPG.
List<KeyValuePair<int, decimal>> weightMPG = new List<KeyValuePair<int, decimal>>();

private void mainForm_Load(object sender, EventArgs e)
{
    decimal k = 7;
    for (int i = 20000; i < 40000; i+=1000){
        weightMPG.Add(new KeyValuePair<int, decimal>(i, k));
        k -= 0.1m;
    }
    for (int i = 40000; i < 45000; i+=1000){
        weightMPG.Add(new KeyValuePair<int, decimal>(i, 5));
    }
    weightMPG.Add(new KeyValuePair<int, decimal>(46000, 4.9m));
    weightMPG.Add(new KeyValuePair<int, decimal>(47000, 4.8m));
    weightMPG.Add(new KeyValuePair<int, decimal>(48000, 4.7m));
    truckWeight2.DataSource = weightMPG;
    truckWeight2.ValueMember = "Value";
    truckWeight2.DisplayMember = "Key";
}

private void truckWeight2_SelectedIndexChanged(object sender, EventArgs e)
{
    truckMPG2.Text = truckWeight2.ValueMember;
}

For this code, it shows a dropdown from 20,000 to 48,000 when I click the control. However when I select one, the textbox (truckMPG2) doesn't update to reflect the value, rather it just always displays word "Value."

I've looked at other stack-overflow answers when making this code, so I'm not sure where I am going wrong.

Upvotes: 0

Views: 124

Answers (1)

David
David

Reputation: 218808

You're reading the .ValueMember property:

truckMPG2.Text = truckWeight2.ValueMember;

Which you specifically set to a literal string:

truckWeight2.ValueMember = "Value";

It sounds like you want the .SelectedValue property instead:

truckMPG2.Text = truckWeight2.SelectedValue;

Or, if the type doesn't match but the value can be directly represented as a string, you might need to append .ToString() to the value:

truckMPG2.Text = truckWeight2.SelectedValue.ToString();

Upvotes: 4

Related Questions