简体   繁体   中英

Can't get Label to display value from combo box selection

C# Winforms User control here.

So I have a label object named alcohol. My combo box object is named snryeastTypeComboBox. I want to keep the number for alcohol for math later. I'm trying to display the number in a label yet it isn't working... any ideas?

public void snryeastTypeComboBox_TextChanged(object sender, EventArgs e)
{
    if (snryeastTypeComboBox.SelectedText == "CSM")
    {
        var alcoholTolerance = 14;
        alcohol.Text = alcoholTolerance.ToString();
    }

Try the following instead:

public void snryeastTypeComboBox_TextChanged(object sender, EventArgs e)
{
    if (snryeastTypeComboBox.Text == "CSM")
    {
        var alcoholTolerance = 14;
        alcohol.Text = alcoholTolerance.ToString();
    }

Replace .SelectedText with just .Text.

To understand your question, I think you need to fire the event when you select a value from your combo box. If that is the case you should subscribe to SelectedIndexChanged event instead of TextChanged .

TextChanged event should be used if the user can change the value by typing in your combo box.

To achieve this your code needs to be written inside the event SelectedIndexChanged instead of TextChanged .

Instead of SelectedText you should use Text

The below code will work fine.

private void snryeastTypeComboBox_SelectedIndexChanged(object sender, EventArgs e)
    {

        if (snryeastTypeComboBox.Text == "CSM")
        {
            var alcoholTolerance = 14;
            alcohol.Text = alcoholTolerance.ToString();
        }

    }

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