Assigning values from one form to the main form

Im trying to assign text to a text box in my main form from code in a differnt form. Both of the forms are open when this takes place and the secondary form closes after it sends the values to the main form, but it dont work.

Heres my code:
frmMain FormMain = new frmMain();
FormMain.txtAmount.Text =
"10000";
FormMain.txtDept.Text =
"%%%%%%%%";


I also tried calling a function in the main form (from formB with the code above) that assigns the value from formB to the correct text box of the main form. I checked with a MessageBox and it sends the correct value to the main form but it doesnt put that value into the text box. I have no idea what the problem could be.

Thanks

Also: I am using VS 2005.


Answer this question

Assigning values from one form to the main form

  • Blisardo

    It seems that you are indeed creating an entirely new 'main' form.
    That's the meaning of the keyword new. Smile

  • AjayShrivastava

    If this is initialization code, then why not preset them in the properties at design time.  Otherwise, if they are dynamic, then they need to be set within the form class itself as a response to an event or in the constructor.  My guess from the limited information provided is you have two instances of that form on the stack while only one is being displayed. 

    Is this the main form of your app


  • DVCasmey

    Thats what I was looking for, it worked great.

     Thanks alot.


  • larange

    There are a few ways to go about this.
    1) pass frmMain instance in the parameter of your child form.
    In frmMain
       childForm frm = new childForm( this );
    In childForm
       childForm( frmMain main )
       {
          //you can set this to a local varaible
       }

    2) Have a public or internal get/set method in the child form.
    In childForm
       public frmMain ParentForm
       {
          get{return prnt;}
          set{prnt = value;}
       }
       private frmMain prnt;
    In frmMain
       childForm frm = new childForm();
       frm.ParentForm = this.

    After you do either one of these you will have access to the main form. You will need to make any accessors on frmMain internal or public though.

  • zam

    I think it might have something to do with the fact that the main form is already open and running in the back ground when this code is executed from the secondary form.
     So does the code above not work with the form thats already running because its a new instance of the frmMain Form and Im trying to change the text of a textbox of the instance thats already running   Just I thought. 

    Anyone have any ideas to help me here

    Thanks

  • Assigning values from one form to the main form