简体   繁体   中英

How do I update a Label when a TextBox value changes?

Is there a way to update a label when entering values into a textBox?

The user can enter their level into a text box, which will then tell them what their multiplier is for that level. At the moment, when the user enters a number into the level field, the multiplier doesn't update until I click into the dropdown menu and reselect the option that I was on before.

For example; if the user enters 50 for their level, then the multiplier will be 1. If they enter >= 92, then the multiplier will show 2. But it doesn't update as a value is being entered into the text box.

Currently, for each object I've placed them in a Switch Case so it's easier to manage.

        private void Level_TextChanged(object sender, EventArgs e)
        {
            RuneMultiplier.Refresh();
        }

level is the textBox that the user is able to put their level in, which should then update the multiplier label.

Well, why don't you make it a bit simple? Something like this ( with your example ):

private void textBox3_TextChanged(object sender, EventArgs e)
{
   if(textBox3.Text == "50")
   {
       label1.Text = (int.Parse(textBox3.Text) * 1).ToString();
   }else if(int.Parse(textBox3.Text) >= 92)
   {
        label1.Text = (int.Parse(textBox3.Text) * 2).ToString(); 
   }
   else
   {
        //this is not a number, some error message idk..
   }       
}

Everytime you entered something in textbox it will update your label or throwing some error depending on your if conditions..

EDIT

Something like this:

private void textBox3_TextChanged(object sender, EventArgs e)
{
switch (int.Parse(textBox3.Text))
{
    case 50:
        label1.Text = (int.Parse(textBox3.Text) * 1).ToString();
    break;
    case int number when number >= 92:
        label1.Text = (int.Parse(textBox3.Text) * 2).ToString();
    break;
    case int number2 when number2 < 50:
        label1.Text = (int.Parse(textBox3.Text) * 0).ToString();
    break;
    default:
        //not a number
    break;
    }
}

There are differnt approches to do that Have a look at the events available on your textbox. For example you can use OnLeave, etc.

A better way is to get notified by the "INotifyChanged" approach which is a fundamental better way to do that from the point of design.

Hopefully this helps you to solve your issue.

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