从ComboBox下拉列表中选择后,文本框不显示值

时间:2017-09-13 20:19:25

标签: c# combobox textbox datasource dropdown

所以我有一个Combo Box,我有一个使用KeyValuePair<int, decimal>制作的列表。当我从下拉文本框中选择它时,我希望我选择的文本框根据键显示值。

相关代码:

// 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;
}

对于此代码,当我单击控件时,它会显示从20,000到48,000的下拉列表。但是,当我选择一个时,文本框(truckMPG2)不会更新以反映该值,而只是始终显示单词&#34;值。&#34;

我在制作此代码时查看了其他堆栈溢出的答案,因此我不确定我哪里出错了。

1 个答案:

答案 0 :(得分:4)

您正在阅读parent.setPopup(popup); 媒体资源:

.ValueMember

您专门设置为文字字符串:

truckMPG2.Text = truckWeight2.ValueMember;

听起来你想要truckWeight2.ValueMember = "Value"; 属性:

.SelectedValue

或者,如果类型不匹配但值可以直接表示为字符串,则可能需要将truckMPG2.Text = truckWeight2.SelectedValue; 附加到值:

.ToString()