How to create a global "C#" class for data base connection such that
?
1. all classes and controls can handle.
2. remian all session untill the main from of an application closed.
3. disconnect from the server when closing windows Form application

I'd recommend against that, actually. It makes managing the connection harder. Also, many database servers will support connection pooling to eliminate the performance cost of creating, opening, and closing a connection for each transaction.

do you mean,
it is better to create connection when needed only, such that click a button or click tabpage ?

Yes.

how about creating a connection in the main form/control and pass the connection details to the constructor of another.

it si a good idea, plz give us an examle that contains multiple forms and controls

consider the case having an mdi parent a child form and a class for handling database connection and queries.
In the MDIParent Form, create an instance of the database class

Database DB = new Database();   /*the constructor of DB automatically opens the connection using the specified connection details.*/

Now create a child form and pass this instance to it.

        private bool CreateMdiChild(string MdiChildName, Form _form)
        {
            foreach (Form MdiChild in this.MdiChildren)
            {
                if (MdiChild.Name == MdiChildName)
                {
                    MdiChild.WindowState = FormWindowState.Normal;
                    MdiChild.BringToFront();
                    return true;
                }
            }

            Form form = _form;
            form.MdiParent = this;
            form.Show();
            return false;
        }



CreateMdiChild("NewChild", new NewChild(this.DB));

In the child form's constructor

Database DB = null;

public NewChild(Database _db)
        {
            InitializeComponent();
            DB = _db;
        }

Now you can use the old instance without creating new.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.