Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing data between form1.cs and program.cs

Tags:

c#

winforms

I know this is really basic, but I couldn't find any guides/tutorials on how to do this between MSDN, Google searches, and stackoverflow.

I created a new Windows Form Application and here I have Program and Form1 where Form1 owns 2 text boxes and buttons.

Button1 is supposed to take the string from Text1 and send it to program.cs where the string gets edited and sent back to Form1. Then Button2 reveals the new string in Text2.

I got as far as obtaining the string from the Text1 (with Button1), but cannot figure out how to send it to program.cs so it can be processed. What exactly am I supposed to do to pass data between the two?

I'm not sure if this is the right start, but I created a myForm in attempts to get the string sent over. But how do I send it back?

In Program.cs:

static Form1 myForm;
[STAThread]
static void Main()
{

    string s1, s2;
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    myForm = new Form1();
    Application.Run(myForm);
    s1 = myForm.sendOver();

}
like image 324
krikara Avatar asked Mar 01 '13 21:03

krikara


People also ask

What is Form1 CS?

form1. cs is the code-behind file of the windows form. It is the class file of the windows form where the necessary methods, functions also event driven methods and codes are written.


1 Answers

You effectively can't. Application.Run(myForm); will block until your form is closed, so it's no longer appropriate to be getting data from it, or giving data to it.

In virtually all winform programs you shouldn't ever be modifying program.cs. While you can occasionally get it to work, it's rarely desirable from a design perspective.

If you want to do processing based on the result of your from, you should most likely be creating an entirely new class, separate from either of these. Call a method from that class (creating an instance of it if appropriate) when appropriate (this may be when a submit button is clicked, in the form closed event handler, etc.).

like image 159
Servy Avatar answered Sep 28 '22 05:09

Servy