C# in form 2 does not show string in label

Asked

Viewed 211 times

0

I don’t understand why Form 2 doesn’t show label text in form 1.

form 1

    private void button1_Click(object sender, EventArgs e)
    {
        string Username = textBox1.Text;
        HelloForm HF = new HelloForm();
        HF.Show();
        HF.Username = Username;
        this.Hide();
    }
}

form 2

    public string Username { get; internal set; }

    private void HelloForm_Load(object sender, EventArgs e)
    {

        label1.Text = "Hello " + Username;
    }
}
  • Put the question in Portuguese.

  • i want the username string of form 1 to appear on label 1 of form 2

  • hehe, I understood what you said in English :P But the site is in Portuguese, got it?

  • thanks I did not know how to edit for en I’m new on this site just now I saw there the edit button

1 answer

1


You need to allow the label1 to be changed by another class. In this case you must change the Modifiers property.

inserir a descrição da imagem aqui

In your case it is not working because the property does not have the value at the time you use it. If you debug, you will see that at the moment, Username has the null value. In this case I indicate you create an overload in the class constructor.

public HelloForm(string _username)
{
    InitializeComponent();
    Username = _username;
}

and then you can simplify the button by using the new constructor.

private void button1_Click(object sender, EventArgs e)
{
    HelloForm HF = new HelloForm(textBox1.Text);
    HF.Show();
    this.Hide();
}

I took the test here and it worked the way you need it.

  • It was already private and is on the label of form 2 not form 1

  • So switch to public. You want to access it publicly and not privately.

  • Didn’t work..

  • See if it helps now.

  • thanks!!! but not everything was necessary

Browser other questions tagged

You are not signed in. Login or sign up in order to post.