Link to home
Start Free TrialLog in
Avatar of lankapala

asked on

C# Forms

My query is , i have 2 forms called Form1 and Form2. Firstly loading Form1, there is command button called cmdButton1 , when its click on the Form2 will show. i need to take form2 values ,there is form2 text box values. need to take back to Form1 text box called txtCatID. i can't use Form1 using new method, using
FORM1 frm1=new FROM1();

it will working, but its creating new form, if like that after user enter  data to Form1 will deleted,b'cos loading as new Form1

i wrote below code but its showing error
public System.Windows.Forms.TextBox txtCatId;

public Form1 frm1;

 frm1.txtCatId.Text = txtCat.Text;

Error showing
NullrefrenceException was handled : Object reference not set to an instance of an object.

Can any one help me to solve above issue.thx
Avatar of MajorBigDeal
Flag of United States of America image

After you create form2 from form1, form1 has a reference to form2 (because you just created it)  but form2 does not have a reference to form1.

So after you create form2,  call a method in form2, passing this (which is form1) and have form2 save the reference to form1.  

Then when you want to manipulate form1 from form2. you have an object reference in form2 that you can work with.
Avatar of Mike Tomlinson
I would show Form2 as a DIALOG so you can simply grab the values off it directly from Form1:

    // ...from within Form1...
    Form2 f2 = new Form2();
    f2.ShowDialog(); // code STOPS here until "f2" is closed
    this.txtCatId.Text = f2.txtCat.Text;

*You need to change the Modifiers() property of "txtCat" on Form2 to Public.
> public Form1 frm1;

Change to a property:

public Form1 Frm1 {get; set;}

As Major says, after Form1 instantiates Form2, set the Frm1 property to contain the reference to the Form1 instance.

Gary Davis
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of lankapala


great thank you very much.
hi fernando ,can you kindly explain why you use below code
f1 = (Form1) Application.OpenForms["Form1"];
specially (Form1).
Hi Iankapala;

In order to write into the text box of Form1 we need a reference to that form. Application.OpenForms is a collection of all open forms and by indexing the collection with the name of the form it will return an object of the form and we need to cast it to the correct form which is Form1. Now that we have a reference to Form1 we can access the public properties of that form.

ok thank you very much. you are excellent
Not a problem, always glad to help.  ;=)