There are lots of questions about the way to declare the global level variable in C#.
If you are true VB programmer, you might have declared public variable in module.bas.
This variable is accessed through out the project. But what about in c#?
Does it support global variable to retain the value in app life time?
Eventhough the answer is Yes, many people does not know to declare global level variable.
Common scenario is global level database variable.
In c#, it is very easy. There is something called static variable. You can use the help of static variable as follows:
In your Program.cs, declare the following variable
public static OdbcConnection myConn= new OdbcConnection();
There should be a function to open the database as follows:
public int DatabaseConnect()
{
try
{
myConn.ConnectionString = strDBConnectionString;
myConn.Open();
if (myConn.State.ToString().Trim() !="Open")//if database connection failed then {
return 0;
}
else
{ return 1;
}
}
catch (OdbcException odbcex)
{
MessageBox.Show(odbcex.Message.ToString());
return -1;
}
}
Since there should be only one datbase instance, you can delcare it as static. To access the static variable, you don't have to create the class instance. In your login screen or MDI screen, you can access the function using the following syntax:
Program.DatabaseConnect();
and you can use the myConn object variable in all windows forms just by calling the myConn variable.
Write me if you have any doubt: soshekar@gmail.com
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment