简体   繁体   中英

Label text isn't updating after updating its text

I use this code but it's not working. what am I doing wrong here?

private void button_input_Click(object sender, EventArgs e)
{
    string input = textbox_input.Text;
    string output = label_output.Text;

    output = input.Replace("a", "4");
    output = input.Replace("s", "5");
    output = input.Replace("e", "3");
    output = input.Replace("v", @"\/");
    output = input.Replace("V", @"\/");
    output = input.Replace("m", "|V|");
    output = input.Replace("M", "|V|");

    input = output;
}

You should assign the output back to the textbox :

label_output.Text = output;

Reason it doesn't work is that though string is a reference type it is immutable. This means that when you use the assignment operator ( = ) a new object is created containing the value. Whenever you apply any changes to the string you are actually creating a new instance with the new value.

Therefore input is not a reference to the same string as textbox_input.Text . And a change on one does not impact the other. Same applies to output and label_output.Text .


As a side note as Replace returns a string you can chain the calls to get a more fluent usage:

label_output.Text - textbox_input.Text.Relace("","").Replace("","").....;

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