Reputation: 249
I am currently working on a C# visual studio windows application. I am having a problem to take a textbox value from one form (Form1) and storing it in a variable for usage in the next form (Form2). I do not want to display the value immediately, therefore i need a way that can store the value in the background and able to use it later on. How can i do it?
I have tried this way but it does not work, anyone can tell me why? The return value in form2 is blank.
Login.cs (Login Page)
public string uname;
private void LoginButton_Click(object sender, EventArgs e)
{
string userName = this.LoginUsernameTextBox.Text;
uname = userName;
}
Form2.cs
private void CheckLoginUsername_Click(object sender, EventArgs e)
{
Login login = new Login();
MessageBox.Show("The value of uname is:" + login.uname);
}
Upvotes: 0
Views: 817
Reputation: 203821
The problem is that Form2
isn't referencing the same instance of Login
that the user is interacting with, you're creating a new instance (never showing it to the user) and then grabbing a value out of that.
You haven't shown the extent of the interactions between these forms (and if you have, you're missing a fair bit).
It should likely look something like this:
In Form2:
private void Form1_Load(object sender, EventArgs e)
{
Login loginForm = new Login ();
loginForm.ShowDialog();
string username = loginForm.UserName;
}
Then the login form should have something like this:
public string UserName { get; private set; }
That will allow you to set the value internally (when the form is submitted/closed) and read it externally.
It's considered poor practice for fields to be public; it's preferable to use properties instead (so that, among other things, you can do what I have done here and restricted the setter to be private).
Upvotes: 2