Hi
I have created below Class. I want connection should be called once for all forms. I am using Windows Form Application
class DBConnection
{
public SqlConnection con;
public void Connection()
{
con = new SqlConnection("Data Source = .;Initial Catalog = Pl_Live; Integrated Security=true;");
}
}
Thanks
Vijay Pratap SinghPosted Apr 19, 2024, 12:31 AM
Hello Ramco,
it seems like you're missing a constructor to initialize the connection.
With this modified class, you can now create an instance of
DBConnectionand call theOpenConnection()method whenever you need to use the connection.Hope this will help.
Thanks
Ashutosh SinghPosted Apr 19, 2024, 11:10 AM
To ensure that the database connection is established once for all forms in your Windows Forms application, you can use a singleton pattern for your
DBConnectionclass. This pattern ensures that only one instance of the class is created and shared across all forms. Here's how you can modify your class:With this setup:
DBConnectionclass has a private constructor to prevent direct instantiation.Instanceproperty is provided to access the single instance of the class.Connectionproperty provides access to theSqlConnectioninstance.Connectionis initialized only once when the class is first accessed.Now, you can use
DBConnection.Instance.Connectionto access the shared connection instance across all forms in your application. For example:This way, you ensure that there's only one database connection instance shared across all forms, and it's initialized only once when first accessed.