简体   繁体   中英

Displaying Text from Combobox Selections C#

I am trying to create a simple Windows Form App in VS 2013 using C#. The form has 2 combo boxes with some strings to select from. 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. 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. 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

Use this SelectedItem instead of SelectedValue

like this

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

You are subscribed to the SelectedValueChanged event.
This event will be fired only when items was added by setting DataSource property

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

Because SelectedValue , in the case when items added manually, will return null

Check this: ComboBox SelectedItem vs SelectedValue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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