Reputation: 25
I'm trying to text passing another form using reader. This code is from Form1.
if (count == 1) // IF Ok.
{
userLabel.Text = myReader[0].ToString(); // SHOW THE USERNAME
loginSuccessTimer1.Enabled = true; // FOR TIMER
LoginFormSuccessBG loginSuccess = new LoginFormSuccessBG();
loginSuccess.Show(); //LoginSuccess SHOW FORM
}
This code from Form2. I want to show text in this form from Form1.
private void button2_Click(object sender, EventArgs e)
{
userLabel2.Text = loginForm.userLabel.Text;
}
But if i click the button2 on Form2; i'm taking this error on Visual Studio:
An unhandled exception of type 'System.NullReferenceException' occurred in Launcher.exe Additional information: Object reference not set to an instance of an object.
I've set the userLabel to public and tried this on Form2.
userLabel2.Text = loginForm.userLabel.ToString();
But it's not working. Always giving this error.
Upvotes: 2
Views: 94
Reputation: 1129
This should work, I just did it in a test app.
userLabel2.Text =
(Application.OpenForms["yourForm1"] as yourForm1).userLabel.Text;
Upvotes: 1
Reputation: 2284
You can pass the Form1 as a parameter to Form2's constructor. Then, if you did userLabel public, so you can access it from Form2. Here is an example:
Form1 code:
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2(this);
frm.Show();
}
Form2 code:
Form1 form1;
public Form2(Form1 sender)
{
InitializeComponent();
form1 = sender;
}
private void button1_Click(object sender, EventArgs e)
{
string text = form1.label1.Text;
}
Upvotes: 1