PMS Tutorial3: Multiple Document Interface (MDI) With Global SQL Local DB Connection

Introduction

In PMS Tutorial2  we have shown how to Update, Delete and Insert records into local database, we also explored how to use the database connection with single form. For an application with many forms the classical way of defining new object from the database connection in each form will not work. Instead, the same database connection must be used in all forms. In this tutorial we explore the Multiple Document Interface MDI, and how to make global database connection so it can be accessed from any form in the application. The tutorial is implemented by Visual Studio 2012. Object Oriented Inheritance will be used in this tutorial, so basic understanding of inheritance should be granted for understanding the contents of this tutorial.

3.1 Multiple Document Interface Main Form


Add new form to be the main form of the project. The main form usually contains the main menu bar, the tools bar and the links to the most important forms. Create new form by clicking the project icon from the solution explorer-> then Add -> then Windows Form



Write frmMain to be the form's name; then click add button. The form is then added to the project. For that new form the following properties must be changed

  1. Text should be changed to "Pharmacy Management Systems PMS".
  2. IsMdiContainer should be changed to True. As shown in the figure, it changes the form type to MDI form
  3. WindowState should be changed to Maximized. This makes the form maximized in startup


If the program is executed (by clicking start) right now it will display the default form; which may not be the main form. To change startup form of the application, the Main() function which holds the starting point of the program should be changed so the first form to be loaded is frmMain. To do that, from the Solution Explorer double click on Program.cs the following code will be displayed

namespace MyPharmacy

{

    static class Program

    {

        /// <summary>

        /// The main entry point for the application.

        /// </summary>

        [STAThread]

        static void Main()

        {

            Application.EnableVisualStyles();

            Application.SetCompatibleTextRenderingDefault(false);

            Application.Run(new Form1());

        }

    }

}


Change Application.Run(new Form1()) to Application.Run(new frmMain()); Then run the program to see which form is displayed first.

3.2 Using Menu Bar to Open Child Forms

Add MenuStrip to the main form as shown in the figure.



Customize the menu bar by adding two main items (File and Screens) then for each item add two subitems. File => New, Screen=>Drugs,Suppliers. As shown in the figure



The menu bar is then used to open all forms of the project.

Create new Table called "Suppliers" then add random records to it, and then create new form called frmSupplier add DataGridView to it as shown in the following figure. If you can't do that, refer to PMS Tutorial1 for full explanation. Prepare the project so the project has two forms One for Suppliers and one for Drugs. You can also use the existing Drug's form from PMS Tutorial2.



To open the two forms using the menu bar, open the main form, then from the menu bar double click on "Drugs" menu item as shown in the figure.



Add the following code

private void drugsToolStripMenuItem_Click(object sender, EventArgs e)

        {

            Form1 frmDrugs = new Form1();

            frmDrugs.ShowDialog();

        }


Since Form1 is the Drugs form, new instance of it is created using the "new" keyword. ShowDialgo() methods displays the form as dialog box inside the main form. Repeat the above procedure for the Supplier form and add the following code

private void suppliersToolStripMenuItem_Click(object sender, EventArgs e)

        {

            frmSuppliers frmSupp = new frmSuppliers();

            frmSupp.ShowDialog();

        }


3.3 Creating Global Database Connection for All forms

The main idea behind making global database connection is to make each separate form inherits not from the "Form" class but from "Customized Form includes DBConnection object". We call the customized form DBConnectionForm, DBConnectionForm inherits from the class "Form". The general outline of project is shown in the following figure



Step 1: Create new class call it "DBConnectionForm", open the code and then add the following code

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

 

namespace MyPharmacy

{

    public class DBConnectionForm:Form

    {

        protected static DBConnection myConnn = new DBConnection();

 

        private void InitializeComponent()

        {

            this.SuspendLayout();

            // 

            // DBConnectionForm

            // 

            this.ClientSize = new System.Drawing.Size(284, 262);

            this.Name = "DBConnectionForm";

            this.ResumeLayout(false);

 

        }

 

    }

}


The above underlined parts of the code only will be added. System.Windows.Forms enables DBConnection to inherit from Form. The inheritance connection is done by DBConnectionForm:Form which enables DBConnectionForm to inherit all functions of the Form class. Finally new variable "myConnn" is defined static so it will be created only once and the same object will be used in all forms of the project.

Step 2: Add connect and disconnect functions of the global database connection to the main form. In the Form_load event add the function for connecting to the database and in the Form_Closing add the function for disconnecting from database as shown in the following code

namespace MyPharmacy

{

    public partial class frmMain :DBConnectionForm 

    {

        public frmMain()

        {

            InitializeComponent();

        }

 

        private void drugsToolStripMenuItem_Click(object sender, EventArgs e)

        {

            Form1 frmDrugs = new Form1();

            frmDrugs.ShowDialog();

        }

 

        private void suppliersToolStripMenuItem_Click(object sender, EventArgs e)

        {

            frmSuppliers frmSupp = new frmSuppliers();

            frmSupp.ShowDialog();

        }

 

        private void frmMain_Load(object sender, EventArgs e)

        {

            myConnn.ConnectToDatabase();

        }

 

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)

        {

            myConnn.Disconnect();

        }

    }

}


So frmMain:DBConnectionForm lets frmMain inherits from the DBConnectionForm. Then myConnn.ConnectToDatabase connects to the database and myConnn.Disconnect() disconnects from the database.

Step 3: Update the database connection "DBConnection" from PMS Tutorial2 to include the following functions

public DataTable getAllDrugs()

        {

            try

            {

                string strCommand = "SELECT * FROM Drugs";

                DataTable dt = new DataTable();

                SqlCeDataAdapter da = new SqlCeDataAdapter(strCommand, conn);

                da.Fill(dt);

                return dt;

            }

            catch (SqlCeException e)

            {

                MessageBox.Show(e.Source + "\n" + e.Message + "\n" + e.StackTrace);

                return null;

            }

        }

 

 

        public DataTable getAllSuppliers()

        {

            try

            {

                string strCommand = "SELECT * FROM Suppliers";

                DataTable dt = new DataTable();

                SqlCeDataAdapter da = new SqlCeDataAdapter(strCommand, conn);

                da.Fill(dt);

                return dt;

            }

            catch (SqlCeException e)

            {

                MessageBox.Show(e.Source + "\n" + e.Message + "\n" + e.StackTrace);

                return null;

            }

        }


Step 4: Open the code of the suppliers form; make an inheritance connection with DBConnectionForm so the connection will be available in the form. Then use the connection to call the getAllSuppliers() method as shown in the following code

namespace MyPharmacy

{

    public partial class frmSuppliers : DBConnectionForm 

    {

        public frmSuppliers()

        {

            InitializeComponent();

        }

 

        private void frmSuppliers_Load(object sender, EventArgs e)

        {

            dataGridView1.DataSource = myConnn.getAllSuppliers();

        }

    }

}


frmSuppliers : DBConnectionForm lets frmSuppliers inherits DBConnectionForm, then dataGridView1.Datasource is filled with the datatable retrieved from the getAllSuppliers function.

Step 5: Repeat step4 for all the remaining forms in the project.

Run the program to make sure every form can display the corresponding database content.

Exercise

Create new project with two forms, the forms are used to display data from the local database. Use the techniques of this tutorial to make MDI application with global connection to the database. 

 


Recommended Free Ebook
Similar Articles