Why won't my C# label text value update?

26,594

Without knowing more about the structure of your form, and how you are calling your code, it's hard to give you any other advice other than to attempt to call lblSesameSeedTotal.Refresh() after setting the text.

Calling Refresh (MSDN Control.Refresh link) effectively invalidates the control and forces the runtime to redraw the control, which, of course, includes updating its text.

There are lots of reasons why you may have to do this; redrawing is an expensive operation, so, in general, if you are handling an event elsewhere on the form, it may not update certain controls. This is especially true for labels and similar controls whose values tend to remain constant (e.g. a label for a textbox with the text: Enter Name Here doesn't really need to change).

Share:
26,594
jrounsav
Author by

jrounsav

Updated on October 23, 2020

Comments

  • jrounsav
    jrounsav over 3 years

    I have a c# program set up that is supposed to accept a quantity input if a checkbox is checked. It then multiplies the quantity by the price and updates the appropriate label with the total cost.

    However, when I run the program it does not update the label. I ran the debugger and the label's .text value in the system is correct but it still does not appear on the actual form.

    Is there a label property in Visual Studio that prevents changes from being rendered?

    here is the snippet responsible for updating the label.Text value

     if (chkSesame.Checked)
        {
            intSesameQty = Convert.ToInt32(txtSesameQty.Text);
            decSesameTotal = intSesameQty * decBAGEL_PRICE;
            lblSesameSeedTotal.Text = decSesameTotal.ToString("c");
        }
    
    • Habib
      Habib about 11 years
      Make sure you are not resetting the value of lblSesameSeedTotal.Text later in your code, also what kind of application are you targeting winfomr, wpf ? web ?
    • jrounsav
      jrounsav about 11 years
      @Habib winform, and I can't find any code overwriting the text :(
    • dash
      dash about 11 years
      In addition to @Habib's useful advice, does calling lblSesameSeedTotal.Refresh() after setting the text value help?
    • jrounsav
      jrounsav about 11 years
      @dash Refresh completely corrected the issue! Thank you both very much
    • Sharique Ansari
      Sharique Ansari about 11 years
      Are you using any update panel?