Mat
Mat

Reputation: 119

Get values from a control in form1 into a new form C#

I am trying to have a click event on a new form that gets the text property of controls in form1.

I have made a public method that returns the values that I need but the returned values are always null. I have looked everywhere for this.

Form1:

public List<string> returner()
{
    List<string> thevalues = new List<string>();

    thevalues.Add(textbox1.Text);
    thevalues.Add(textbox2.Text);

    return thevalues;
}

Form2:

Form1 x = new Form1();

List<string> values = x.returner();
label1.Text = values[0];
label2.Text = values[1];

My issue is that there are no values returned because Im declaring a new instance of Form1 rather than using the one that has values in it (I guess).

Upvotes: 1

Views: 219

Answers (2)

Jey
Jey

Reputation: 1511

you've messed up with your codes.. if you want to get a value of text just use this. string textValue = form1.textbox1.Text or.. since you didnt post the full code here.. try this rather than creating the object form1.returner();

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499830

Yes, that would explain what's going wrong. Basically you need to tell Form2 about the relevant instance of Form1. Exactly how you do that will depend on what constructs everything. For example, you might have:

Form1 form1 = new Form1();
Form2 form2 = new Form2();
form2.Form1 = form1;

Or you could pass the reference in the constructor to Form2.

If those are really the names of your forms, by the way, I'd strongly advise you to rename them to something more meaningful - something which indicates the purpose of the form. Likewise returner not only violates .NET naming conventions, it also doesn't explain what it's doing.

Upvotes: 1

Related Questions