Hey guys,

need your help once again. I want to create a global variable in
one form and then use it in another form.
I need to know of it is possible. If yes, then how do we do it.


Thanks And regards

Yes it is, but you can pass it between classes as parametes, or directly if you mark is as public.

Example:

public class Class1
    {
        private string variable1;


        public Class1()
        {
             //constructor of class1
        }

        private void MethodInClass1()
        {           
            variable = "a1";
            Class2 c2 = new Class2();
            c2.var2 = "b2"; //if you set the variable as public, you can access it directly (but this is a bad practice).
            c2.MethodInClass2(variable1);
            
        }
    }

    public class Class2
    {       
        private string var1;
        public string var2;
        
        public Class2()
        {
            //constructor of class2
        }

        public void MethodInClass2()
        {
            MessageBox.Show("2. " + var1 + " AND " + var2);
        }
    }

You can pass the params in the constructor of the class well:

public class Class1
    {
        private string variable1;


        public Class1()
        {
             //constructor of class1
        }

        private void MethodInClass1()
        {           
            variable = "a1";
            Class2 c2 = new Class2(variable1);
            
        }
    }

    public class Class2
    {       
        private string var1;       
        
        public Class2(string value)
        {
            //constructor of class2
            var1 = value;
            MethodInClass2();
        }

        public void MethodInClass2()
        {
            MessageBox.Show("2. " + var1 + " AND " + var2);
        }
    }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.