Reputation: 11
I've already searched other questions for this answer (and that is how I got as far as I did) and everything seems to be working except the end result. I am getting no errors but I am not getting the desired input and cannot figure out why.
I have two forms, Form1 and login. On Form1 I have a label called "label2" that is going to display text entered from a textbox on login upon button press. Here is the code I have so far:
Form1 Code:
public void SetTextForLabel(string myText)
{
this.label2.Text = myText;
}
login Code:
private void button1_Click(object sender, EventArgs e)
{
Form1.userName = textBox1.Text;
Form1.password = textBox2.Text;
Form1 frm = new Form1();
frm.SetTextForLabel(textBox1.Text);
this.Close();
}
The program works. I click login on form1, it opens up the login form. I enter my username and password and it passes the input to my form1 variables. Since label2 on form1 is not public, I made a public method to use on my login form that will change my label2.Text, but it doesn't and I'm not sure why. Any help would be appreciated.
Upvotes: 0
Views: 2002
Reputation: 43300
Judging from your description, I believe Form1 opens Login form, and on login form there is button1
that is probably your login button.
If this is all correct then I think you have your logic wrong.
your button on Form1 that opens login form should do the following
using(Login loginForm = new Login())
{
if(DialogResult.OK == loginForm.ShowDialog())
{
SetTextForLabel(loginForm.TextAccessorProperty);
}
else
{
MessageBox.Show("Invalid login");
}
}
then login forms button one should just do,
//Login logic
this.DialogResult = DialogResult.OK;
// (no need for form.close())
Upvotes: 1
Reputation: 3860
Your code works fine for me, Just write one more line to show form1.
i.e.
frm.Show();
I think it will work. :)
Upvotes: 0
Reputation: 54761
This creates a new instance of Form1
but it's not shown, and I suspect this is not the reference you need.
Form1 frm = new Form1();
frm.SetTextForLabel(textBox1.Text);
Upvotes: 0