How to get a variable's value after hiding a form?

Socarsky

Well-known member
Joined
Mar 3, 2014
Messages
59
Programming Experience
Beginner
How to get a variable's value after hiding a form?
I need to get a string variable's value after hiding a form from another form.

I used a property for that but it does not work.

Form1's code:
private string strPSqlDBname;        

        public string passDBname
        {
            get { return strPSqlDBname; }
            set { strPSqlDBname = value; }
        }

        internal void populate()
        {
            passDBname = txtPervasiveDBName.Text;
        }

Hide();
                    using (Form2 fmr2 = new Form2())
                        frm2.ShowDialog();
                    Application.Exit();


Form2's code:
string getDBname;
Form1 frm1 = new Form1();
            frm1.populate();
            getDBname = frm1.passDBname;
            string ConnStrPSql = "Server Name=xxxxx;Database Name='" + getDBname + "';User ID=administrator;Password=xxxxx;";
 
Last edited:
You're not hiding any form there. You're not showing it in the first place so how could you be hiding it? If you never show the form then why would there be any text in that TextBox?
 
Solution

The problem with your code is:
Form1 frm1 = new Form1();

Above statement creates a new instance (object) of Form1 so the textbox txtPervasiveDBName will be newly created everytime the above statement is executed.

You can store the Database name to be passed in Program.cs file.
Create a static property in program.cs.

Program.cs:
private static string DBName;
        
public static string PassDBName
{
     set{ DBName = value; }
     get{ return DBName; }
}


Form1:
Program.PassDBName = txtPervasiveDBName.Text; //Store DB Name before hiding Form1
this.Hide(); //or simply Hide();


Form2:
private string GetDBName, ConnStrPSql;

GetDBName = Program.PassDBName;
ConnStrPSql = "Server Name=xxxxx;Database Name='" + GetDBName + "';User ID=administrator;Password=xxxxx;";
 
Last edited:
The problem with your code is:

You can store the Database name to be passed in Program.cs file.
Create a static property in program.cs.
Appreciated that you have showed me right approach. Actually I thought that but I forced myself to handle with my way. Project Properties usage is easy and simple way.
 
Back
Top Bottom