0

I'm new to C# and Winforms.

I have been trying to pass the username variable from form 1 to be used in form 3 and it is not working. I have been searching forever for a solution and I am confused as to why it is not working. In the label, nothing is showing up except for the string. Any help is appreciated!

FORM 1:

public static string username;

private void btn_login_Click(object sender, EventArgs e)
{
if (successfulLogin == true)
            {

                username = tb_username.Text;
                Form3 form = new Form3();
                form.Show();
                this.Hide();
            }
            else
            {
                MessageBox.Show("Log in unsuccessful. Please make sure your credentials are correct or sign up");
                tb_password.Clear();
                tb_username.Clear();
                tb_username.Select();
            }
}

FORM3:

public Form3()
        {
            InitializeComponent();
            usernameChange();
        }

private void usernameChange()
        {
            label1.Text = Form1.username + ", please create, review or manage your flashcards below";
        }
Ethan H
  • 9
  • 2
  • "and it is not working" Why is it not working? Is something else displayed as expected? Do you get an exception or a compiling error? – SomeBody May 17 '21 at 10:53
  • Sorry, I realised this after I posted it. Nothing shows up in the label except for the string @SomeBody – Ethan H May 17 '21 at 10:54
  • @jdweng: It seems that you have posted the wrong link... – Heinzi May 17 '21 at 10:54
  • @EthanH Are you sure that `tb_username.Text` is not an empty string? Because the code you showed us looks fine. – SomeBody May 17 '21 at 11:00
  • @SomeBody It shouldn't be because it is used for login and works fine. – Ethan H May 17 '21 at 11:01
  • You need to use an instance of the form. See my two form project : https://stackoverflow.com/questions/34975508/reach-control-from-another-page-asp-net?force_isolation=true – jdweng May 17 '21 at 11:06
  • 1
    Do you by any chance clear the textbox text after you login successfully? – crankedrelic May 17 '21 at 13:06
  • 1
    static references for these reasons aren't the best way to go. Better change your Form3 constructor to Form3(string username) and pass the username this way when you instantiate the form. – crankedrelic May 17 '21 at 13:10
  • 1
    Does this answer your question? [passing values between forms (winforms)](https://stackoverflow.com/questions/3062575/passing-values-between-forms-winforms) and [Passing variable between winforms](https://stackoverflow.com/questions/4247807/passing-variable-between-winforms) and [Communicate between two windows forms in C#](https://stackoverflow.com/questions/1665533/communicate-between-two-windows-forms-in-c-sharp) –  May 17 '21 at 13:41

0 Answers0