Click here to Skip to main content
15,885,127 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello guys.
I declare a public variable in a windows Form and it initializes with a string in this form
Now i wanna use this variable in other form.but variable in new form is null.
What am i doing ?
plz help
Posted
Comments
CPallini 4-Mar-13 4:25am    
How do you access the variable?
Anurag Sinha V 4-Mar-13 4:27am    
Hi, Can you post the code as to what have you done?
It will be quite easy to catch the bug or else..

regards
anurag
prashant patil 4987 4-Mar-13 4:40am    
make it Null in Every Page Load.
[no name] 4-Mar-13 14:42pm    
Why don't you just pass the variable in the form's constructor?

Add new module of class and declare this variable as public in this module.

More about scoping in C#: http://msdn.microsoft.com/en-us/library/aa691132%28v=vs.71%29.aspx[^]

Example: http://stackoverflow.com/questions/2445436/global-variables-in-c-net[^]
 
Share this answer
 
v3
Use a separate class file...
C#
public static class GlobalVar
    {
        /// <summary>
        /// Global variable that is constant.
        /// </summary>
        public const string GlobalString = "Important Text";

        /// <summary>
        /// Static value protected by access routine.
        /// </summary>
        static int _globalValue;

        /// <summary>
        /// Access routine for global variable.
        /// </summary>
        public static int GlobalValue
        {
            get
            {
                return _globalValue;
            }
            set
            {
                _globalValue = value;
            }
        }

        /// <summary>
        /// Global static field.
        /// </summary>
        public static bool GlobalBoolean;
    }
 
Share this answer
 
Comments
fjdiewornncalwe 4-Mar-13 13:20pm    
Please cite the source when you copy/paste an answer from somewhere else: In this case the source is here: Clickey
If you want a variable to be accessed from anywhere then you should declare that as static. In that case once initialized - that value can be read from anywhere in the project.
 
Share this answer
 
It sounds like you doing something like this:

public class MyForm : Form
{
	public void foo()
	{
		Data = "balbla";
	}
	public string Data;
}

public void bar()
{
	MyForm form1 = new MyForm();
	form1.foo();
	
	MyForm form2 = new MyForm();
	Console.WriteLine(form2.Data);
}



and your getting null.

in which case you should make Data static:

public static string Data;


now you will get "blabla".
 
Share this answer
 

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