Hi I am learning C#.
I created two forms. Form1, Form2.
Inside the program.cs -> static class Program -> static void Main() -> I am doing Application.Run(new Form1());
I have a public variable in Form1. That is "public static int myCode";
Inside the Form1-> There is a button -> button1.
I wrote a code like, button1_click(... ..)-> Form2 frm = new Form2(); frm.Show();

But here inside the form2 i want to show the value of Form1's variable that is "myCode". I am not able to access it. How to get that value to Form2.

I tried to have a public static function and tried to return the value of the "myCode". But it is showing error "not all codepaths return a value"

Then I tried to change some thing in Program.cs like create a Form1's object -> Form1 frm; and then inside main() -> frm = new Form1(); and then wrote that Application.Run(frm);
But here also i am getting some other error.

How can i access myCode from first form to Form2? Please share answer. Thanks in advance.

7 Years
Discussion Span
Last Post by jonsca

Modify the constructor of Form2 to take a reference variable of myCode's type, pass it in when you instantiate form2 in form1.

The not all codepaths return a value just means that, well, there are paths through that method that do not have a return value (like an if, else if that doesn't have a closing else or a return value in a loop).
Search around the forum some because this question gets asked quite frequently.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.