baban jamal baban jamal - 1 month ago 8
C# Question

One connection for whole of the form

hi guys I have this connection and I have to type it every time when I need my db is there any way to type it once and using it in every button by

con.open();
and
con.close();


OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "\\db\\it.accdb");

Amy Amy
Answer

Yes. Use a function.

private OleDbConnection GetConnection()
{
    return new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "\\db\\it.accdb");
}

Then when you need a connection, call it:

var con = GetConnection();

Functions promote code re-use. This code can further be improved by moving the connection string into a configuration file.

Comments