Hey the solution you are going to use is not a way.if you want to achieve it you need to follow the concept of Object-Oriented Programming Methodology in which you create a class for your MySQLConnection and then use as many time as you want.
take a look how you will create it.
Create a
class
and create a
static
method
public class myConnection
{
public static MySqlConnection GetConnection()
{
string str = "SERVER=localhost;"+"DATABASE=mydatabase;"+"UID=testuser;" + "PASSWORD=testpassword;";
MySqlConnection con = new MySqlConnection(str);
con.Open();
return con;
}
}
if you want to pass value in connection string at runtime then you can use it
class myConnection
{
public static string datasource = "";
public static string initialcatalog = "";
public static string uid = "";
public static string pwd= "";
public static MySqlConnection GetConnection()
{
string str = "SERVER='"+datasource+"';DATABASE='"+initialcatalog+"';UID='"+uid+"';PASSWORD='"+pwd+"'";
MySqlConnection con = new MySqlConnection(str);
con.Open();
return con;
}
}
and then go to Form where you are going to Enter data for Connection Strng and then look how you will pass value in myConnection Class.
let this code is place in click event of connect button or any where you want as your requirement
MyConnection.datasource = txtdatsource.Text;
MyConnection.initialcatalog = txtdatabase.Text;
MyConnection.uid = txtuid.Text;
MyConnection.pwd = txtpwd.Text;
now when you can use
myConnection.GetConnection(); instead of creating a new connection.
when ever you call it it will give you a connection.
Make Once, use More than Once....