简体   繁体   English

从组合框选择中显示文本C#

[英]Displaying Text from Combobox Selections C#

I am trying to create a simple Windows Form App in VS 2013 using C#. 我正在尝试使用C#在VS 2013中创建一个简单的Windows Form App。 The form has 2 combo boxes with some strings to select from. 该表格有2个组合框,其中有一些字符串可供选择。 I am trying to display results in 2 text boxes based upon those selections, but when I run the program the results do not display. 我试图根据这些选择在2个文本框中显示结果,但是当我运行程序时,结果不显示。 I placed the code in the method for selecting values from the combo boxes. 我将代码放在用于从组合框中选择值的方法中。 Here is what I have: 这是我所拥有的:

private void SiteList_SelectedValueChanged(object sender, EventArgs e)
{
    string SiteSelect = SiteList.SelectedValue.ToString();
    string DateSelect = dateList.SelectedValue.ToString();


   if (SiteSelect == "Alaska"  &&  DateSelect = "January 2014")
   {
       actualResults.Text = "$391,015.92";
       estimateResults.Text = "No Estimate Available";
   } 
}

try this instead : 试试这个代替:

string SiteSelect = SiteList.SelectedItem.ToString();
string DateSelect = dateList.SelectedItem.ToString();

SelectedItem is the way to select the object in the comboBox. SelectedItem是在comboBox中选择对象的方法。 Value will select only the display string (I don't know why but it doesn't work all the time). 值将仅选择显示字符串(我不知道为什么,但并非一直如此)。 I always use SelectedItem with toString() to get the object as string 我总是将SelectedItem与toString()一起使用以将对象作为字符串获取

Use this SelectedItem instead of SelectedValue 使用此SelectedItem代替SelectedValue

like this 像这样

string Site = SiteList.SelectedItem.ToString();
string Date = dateList.SelectedItem.ToString();

You are subscribed to the SelectedValueChanged event. 您已订阅SelectedValueChanged事件。
This event will be fired only when items was added by setting DataSource property 仅当通过设置DataSource属性添加了项目时,才会触发此事件

Me.ComboBox.DataSource = yourListOfItems;

If items was added manually (as I assume) 如果项目是手动添加的(按照我的假设)

Me.ComboBox.Items.Add(yourNextItem);

Then you need to subscribe to the SelectionChangesCommitted event And as other answers said use SelectedItem for getting selected value 然后,您需要订阅SelectionChangesCommitted事件,如其他答案所述,请使用SelectedItem获取所选值

Because SelectedValue , in the case when items added manually, will return null 因为SelectedValue在手动添加项目的情况下将返回null

Check this: ComboBox SelectedItem vs SelectedValue 检查一下: ComboBox SelectedItem与SelectedValue

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM