Click here to Skip to main content
15,886,518 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have a code like this :
C#
int a;
                  a=Convert.ToDouble(textbox1.text);

and i cant use "a" variable in another windows form or class.when i want to insert the code in a public class to use it globally the text box is not available.does any body knows how to use that variable globally or declare it globally without inserting it in a class?
Posted
Updated 27-May-15 8:13am
v2

Don't.
While it's possible - you can declare it as a static class member as Shmuel Zang suggests, that's generally evidence of poor design and a massive kludge going on to get round it. Mostly because there is only ever one single instance of a static variable per application, and that means that if you ever try to re-user you form or code, you will start to get strange errors creeping in.

Generally speaking you should pass the value to the class (or form) if you created the instance, or signal an event to allow your "creator" to fetch the value and pass it to the appropriate class.

Have a look at these:
Transferring information between two forms, Part 1: Parent to Child[^]
Transferring information between two forms, Part 2: Child to Parent[^]
Transferring information between two forms, Part 3: Child to Child[^]
They will probably cover what you are trying to do in a more OOPs friendly way.
 
Share this answer
 
Comments
Shmuel Zang 27-May-15 11:13am    
5'ed. Using global variables is really not an OOP's best practice. But, maybe this is what the asker wants. :)

You can define it as a static class member.


For instance, you can create a static class for holding the whole of the variables that are used globally:


C#
static class MyGlobals
{
    public static double a;
}

Then, you can use it in your form and, in other forms:


C#
MyGlobals.a = Convert.ToDouble(textbox1.text);
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900