I am creating a form in c# so any new form inheritances the property of build in class From
I also created a class called program which starts a connection to my Database I would like all my forms to inherit it because I don’t want to open a new connection for every form
i cant use interface because program contains main() where it creates a connection
My program class is
class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
MySqlConnection myConnection = new MySqlConnection("Server=instance2813231.db.xeround.com;Port=18422;Database=shares info;Uid=user;Pwd=password;");
MySqlCommand command = myConnection.CreateCommand();
try
{
myConnection.Open();
MessageBox.Show("connected");
}
catch (Exception a)
{
Console.WriteLine(a.ToString());
MessageBox.Show("Failed");
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
How can I get around this?
Ick, don’t. It’s an abuse of inheritance in order to achieve code reuse in a very poor way.
Firstly, try to separate your GUI code from your database code.
Secondly, favour composition over inheritance – a form isn’t logically a
Programor a “database connection opener”. It should use the latter, but it isn’t one. You should have a single entry point, which instantiates whatever it needs to, then starts things running.Thirdly, don’t use a single connection through your code – instead, open and close connections as you need to, and let connection pooling take care of the efficiency aspect.
So instead of deriving from the class, provide each form with a reference to an instance of your database connection opener (if you really want to mix your database and GUI code… ick), and then your form can use that opener.