dim mik dim mik - 1 month ago 9
C# Question

Passing values through forms c#

I am building a form application at Visual Studio 2015 in C#. First of all i've made a user login form using 2 textboxes and 1 button. All i want to do is to pass the value from the textbox that contains username to a label which is located to another form which form is called MainMenu. This is my code for the button i made to the login form:

private void button_login(object sender, EventArgs e)
{
MainMenu username = new MainMenu();
username.Value1 = textBox1.Text;
this.Hide();
MainMenu ss = new MainMenu();
ss.Show();
}


and the code for the MainMenu form that i want to pass the value is the following:

private string value1 = string.Empty;
public string Value1
{
set { value1 = value; }
get { return value1; }
}
private void MainMenu_Load(object sender, EventArgs e)
{
label7.Text = Value1;
}


As you can see i have create a property in MainMenu form that is accessible from login form so i could transfer the value from textbox1 directly in your MainMenu form. The problem is that the text in label7 remains empty during runtime and i can't understand why. Am i missing something from my code or i am doing something completely wrong ?
Any suggestions would be appreciated

Answer

You actually create two Forms: username and ss. You set Value1 of username, but you show ss which you didn't set its Value1. So you should show username:

private void button_login(object sender, EventArgs e)
{
   MainMenu username = new MainMenu();
   username.Value1 = textBox1.Text;

   this.Hide();
   username.Show(); // and not ss.Show();
}

Also, a tip, use better names for your variables. The code below do exactly the same thing but is much more comprehensible:

private void loginButton_Click(object sender, EventArgs e)
{
   MainMenu mainMenuForm = new MainMenu();
   mainMenuForm.UserName = userNameTextBox.Text;

   this.Hide();           
   mainMenuForm.Show();
}

class MainMenu : Form
{
    // This is an "Auto-Implemented Property".
    // Auto-Implemented Properties are used as a shortcut of what you have done.
    // Google them for more information.
    public string UserName { get; set; }

    private void MainMenu_Load(object sender, EventArgs e)
    {
        userNameLabel.Text = UserName;
    }
}