Click here to Skip to main content
15,881,751 members
Articles / Desktop Programming / WTL
Article

WTL MDI Application with Splitter

,
Rate me:
Please Sign up or sign in to vote.
4.90/5 (12 votes)
12 Oct 20022 min read 142.2K   3.5K   25   27
This article describes how to use an MDI client in a splitter pane of a WTL MDI application with splitter window.

WTL MDI Splitter Sample

Introduction

This article explains how to use WTL's CSplitterWindow class in an MDI application. The sample project included with this article is a wizard-generated MDI application enhanced with a two pane vertical splitter. On the left side of the splitter is the About dialog (thus no Help menu) and on the right side is the MDI client window.

Main Frame

Most of the relevant code for using the splitter window is contained in the mainframe.h file of the sample project. The splitter is initialized in OnCreate() by calling the CreateClient() method and assigning the result to m_hWndClient. CreateClient() sets up the left and right panes, issues a call to CreateMDIClient(), and assigns that result to m_hWndMDIClient. It is important to change the parent of the MDI client to the splitter, as shown below.

// Create and populate the spltter window
HWND CreateClient()
{ // Get the Client RECT for the entire window as a starting size
  RECT rcClient;
  GetClientRect(&rcClient);

  // Create the vertical splitter. This is the main window
  m_splitter.Create(m_hWnd, rcClient, NULL, WS_CHILD | WS_VISIBLE |
		    WS_CLIPSIBLINGS | WS_CLIPCHILDREN);

  // Create the About dialog in the left pane
  m_about.Create(m_splitter.m_hWnd);
  m_splitter.SetSplitterPane(SPLIT_PANE_LEFT, m_about.m_hWnd);

  // Create the MDI client in the right pane
  m_hWndMDIClient = CreateMDIClient();
  m_splitter.SetSplitterPane(SPLIT_PANE_RIGHT, m_hWndMDIClient);

  // IMPORTANT! Make the splitter the parent of the MDI client
  ::SetParent(m_hWndMDIClient, m_splitter.m_hWnd);

  m_splitter.SetSplitterPos(132); // from left

  // Splitter is ultimately the client of Main Frame (m_hWndClient)
  return m_splitter.m_hWnd; }

In addition, a modification is made to the OnFileNew handler so that the child window is assigned the proper parent: pChild->CreateEx(m_hWndMDIClient). It is important to use the MDI client handle when carrying out operations of this sort, since m_hWndClient refers only to the splitter window.

Child Frame

The relevant code for handling child window activation is contained in the childfrm.h file of the sample project. A child window with an edit control view is initialized and assigned an icon in OnCreate(). In addition, a window message, WM_MDIACTIVATE, is overriden to ensure proper title bar and menu activation and deactivation. Here is the handler code:

LRESULT OnMDIActivate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{ // Child to deactivate
  ::SendMessage((HWND)wParam, WM_NCACTIVATE, FALSE, 0);

  // Child to activate
  ::SendMessage((HWND)lParam, WM_NCACTIVATE, TRUE, 0);

  // Set focus to the MDI client
  ::SetFocus(m_hWndMDIClient);

  // Switch to child window menu or back to default menu
  if((HWND)lParam == m_hWnd && m_hMenu != NULL)
  { HMENU hWindowMenu = GetStandardWindowMenu(m_hMenu);
    MDISetMenu(m_hMenu, hWindowMenu);
    MDIRefreshMenu();
    ::DrawMenuBar(GetMainFrame()); }
  else if((HWND)lParam == NULL) // last child has closed
    ::SendMessage(GetMainFrame(), WM_MDISETMENU, 0, 0);

  bHandled = FALSE;
  return 1; }

The GetMainFrame() method called in OnMDIActivate() is a simple wrapper function that accounts for the splitter window as follows:

HWND GetMainFrame() { return ::GetParent(GetMDIFrame()); }

Finally, another window message, WM_MENUSELECT, is overriden to allow activation of the child window's system menu (upper left title bar icon), like this:

LRESULT OnMenuSelect(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL&)
{ return ::SendMessage(GetMainFrame(), uMsg, wParam, lParam); }

Additional Stuff

The sample project also has a few helper routines in mainframe.h that work with the UpdateUI mechanism to enable/disable menu and toolbar buttons when a child window and its edit control are active. A WTL class, CEditCommands is inherited by the view (mdisplitview.h) to provide standard undo, cut, copy, and paste functions for the edit control.

The sample project also uses two WTL message map macros to exchange commands between the main frame and child frame. CHAIN_MDI_CHILD_COMMANDS() is added to the main frame message map and CHAIN_CLIENT_COMMANDS() is added to the child frame map so that edit commands are available from the main menu and toolbar as well as the edit control's popup menu.

Terms Of Use

The sample application available with this article is free for any purpose.

THIS SOFTWARE IS DISTRIBUTED AS-IS, WITHOUT WARRANTIES OF ANY KIND.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Founder Choycer
United States United States
Ed has over 40 years experience in computer technology and a bachelor's degree in Business Administration. He's currently a marketing technology consultant. During his career, he's led software development departments and created software still in use in the communications and healthcare industries. Ed is a veteran of the United States Army. He lives in Arizona in the United States.

Find Ed on Linkedin.

This material is copyright 2019 by Ed Gadziemski. Unauthorized use is strictly prohibited. All rights reserved.

Written By
Software Developer (Senior) Gremlin Games
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
NewsNice Article Pin
Prafull_neo_code12-Jan-12 2:39
Prafull_neo_code12-Jan-12 2:39 
GeneralRe: Nice Article Pin
Prafull_neo_code18-Jan-12 19:46
Prafull_neo_code18-Jan-12 19:46 
Main Form

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;

namespace TestAsync
{
    public partial class SQLMain : Form
    {
        SQLOrder[] orderForm = new SQLOrder[GlobalForms.TotalTables];
        DataTable emptyDT = null;
        public static DataTable tempDT;

        string strCon = System.Configuration.ConfigurationSettings.AppSettings["connString2"].ToString();
        SqlConnection conn;

        // The PrintDocument to be used for printing.
        //PrintDocument MyPrintDocument;
        // The class that will do the printing process.
        DataGridViewPrinter MyDataGridViewPrinter;

        public SQLMain()
        {
            InitializeComponent();

            this.dgvListOrder.CellContentClick += new DataGridViewCellEventHandler(dgvListOrder_CellContentClick);
       
            dgvListOrder.Rows.Clear();
            dgvListOrder.Columns.Clear();
            
            DataGridViewButtonColumn btnTable = new DataGridViewButtonColumn();

            btnTable.HeaderText = "Table";
            btnTable.Name = "btnTable";
            btnTable.Text = "Table";
            dgvListOrder.Columns.Add(btnTable);

            DataGridViewTextBoxColumn txtTotal = new DataGridViewTextBoxColumn();

            txtTotal.HeaderText = "Item";
            txtTotal.Name = "Item";
            //txtTotal.Text = "Table";
            dgvListOrder.Columns.Add(txtTotal);

            DataGridViewButtonColumn btnUpdate = new DataGridViewButtonColumn();

            btnUpdate.HeaderText = "Update";
            btnUpdate.Name = "btnUpdate";
            btnUpdate.Text = "Table";
            dgvListOrder.Columns.Add(btnUpdate);

            //DataGridViewImageColumn img = new DataGridViewImageColumn();

            //Image image = Image.FromFile(@"D:\Table1.bmp");
            //img.Image = image;
            //img.HeaderText = "ImageHeader";
            //img.Name = "Image";

            //dgvListOrder.Columns.Add(img);

            for (int i = 0; i < GlobalForms.TotalTables; i++)
            {
                string[] row = new string[] { "Table" + (i + 1), "TotalPrice", "Update" };
                dgvListOrder.Rows.Add(row);

                orderForm[i] = new SQLOrder();
            }

            dgvListOrder.Columns[1].ReadOnly = true;
        }

        private void dgvListOrder_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            lblTotal.Text = "0";
            if (e.RowIndex > -1 && e.ColumnIndex == 0)
            {
                int tblNo = e.RowIndex + 1;

                GlobalForms.strTableNo = "Table-" + tblNo;
                GlobalForms.selectedTable = tblNo;
                
                orderForm[e.RowIndex].ShowDialog();
                fillGrid();
                calculateTotal();

                //if (orderForm[e.RowIndex].DialogResult == System.Windows.Forms.DialogResult.OK)
                //    dgvOrderDetails.DataSource = null;
                //else
                //    fillGrid();
            }

            if (e.RowIndex > -1 && e.ColumnIndex == 1)
            {
                GlobalForms.selectedTable = e.RowIndex + 1;
                fillGrid();
            }
        }

        private void fillGrid()
        {
            // Fill 2nd Grid

            conn = new SqlConnection(strCon);
            SqlDataAdapter da;
            DataTable dt = new DataTable();
            string strCommand;

            strCommand = "select Item, Price from zTable" + GlobalForms.selectedTable;
            conn.Open();

            da = new SqlDataAdapter(strCommand, conn);
            da.Fill(dt);
            dgvOrderDetails.DataSource = dt;
            conn.Close();

            calculateTotal();
        }

        private void calculateTotal()
        {
            double sum = 0;

            foreach (DataGridViewRow row in dgvOrderDetails.Rows)
            {
                sum += Convert.ToDouble(row.Cells[1].Value);
            }

            lblTotal.Text = sum.ToString();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            conn = new SqlConnection(strCon);

            string[] strCommand = new string[GlobalForms.TotalTables];

            for (int i = 0; i < GlobalForms.TotalTables; i++)
            {
                strCommand[i] = "create table zTable" + (i + 1) +
                             " (ID int IDENTITY(1,1) NOT NULL, Item varchar(50), Price numeric(18,2))";
                conn.Open();
                SqlCommand cmd = new SqlCommand(strCommand[i], conn);

                cmd.ExecuteNonQuery();
                conn.Close();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            conn = new SqlConnection(strCon);

            string[] strCommand = new string[GlobalForms.TotalTables];

            for (int i = 0; i < GlobalForms.TotalTables; i++)
            {
                strCommand[i] = "drop table zTable" + (i + 1);
                conn.Open();
                SqlCommand cmd = new SqlCommand(strCommand[i], conn);

                cmd.ExecuteNonQuery();
                conn.Close();
            }
        }

        private void SQLMain_Load(object sender, EventArgs e)
        {
            dgvOrderDetails.DataSource = null;
        }

        private void btnCheckOut_Click(object sender, EventArgs e)
        {
            conn = new SqlConnection(strCon);

            string strCommand;

            strCommand = "truncate table zTable" + GlobalForms.selectedTable;
            conn.Open();
            SqlCommand cmd = new SqlCommand(strCommand, conn);

            cmd.ExecuteNonQuery();
            conn.Close();

            int tempT = GlobalForms.selectedTable - 1;
            orderForm[tempT].dgvOrderList.DataSource = emptyDT;

            // Printing DataGridView

            //if (SetupThePrinting())
            //    MyPrintDocument.Print();

            //******


            dgvOrderDetails.DataSource = null;
        }      

        private void SQLMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                conn = new SqlConnection(strCon);

                string[] strCommand = new string[GlobalForms.TotalTables];

                for (int i = 0; i < GlobalForms.TotalTables; i++)
                {
                    strCommand[i] = "drop table zTable" + (i + 1);
                    conn.Open();
                    SqlCommand cmd = new SqlCommand(strCommand[i], conn);

                    cmd.ExecuteNonQuery();
                    conn.Close();
                }
            }
            catch
            { }
        }

        // The printing setup function
        private bool SetupThePrinting()
        {
            PrintDialog MyPrintDialog = new PrintDialog();
            MyPrintDialog.AllowCurrentPage = false;
            MyPrintDialog.AllowPrintToFile = false;
            MyPrintDialog.AllowSelection = false;
            MyPrintDialog.AllowSomePages = false;
            MyPrintDialog.PrintToFile = false;
            MyPrintDialog.ShowHelp = false;
            MyPrintDialog.ShowNetwork = false;

            if (MyPrintDialog.ShowDialog() != DialogResult.OK)
                return false;

            MyPrintDocument.DocumentName = "Bill Print";
            MyPrintDocument.PrinterSettings = MyPrintDialog.PrinterSettings;
            MyPrintDocument.DefaultPageSettings = MyPrintDialog.PrinterSettings.DefaultPageSettings;
            MyPrintDocument.DefaultPageSettings.Margins = new Margins(40, 40, 40, 40);

            if (MessageBox.Show("Do you want the report to be centered on the page",
                "BillManager - Center on Page", MessageBoxButtons.YesNo,
                MessageBoxIcon.Question) == DialogResult.Yes)
                MyDataGridViewPrinter = new DataGridViewPrinter(dgvOrderDetails,
                MyPrintDocument, true, true, "Bill", new Font("Tahoma", 18,
                FontStyle.Bold, GraphicsUnit.Point), Color.Black, true);
            else
                MyDataGridViewPrinter = new DataGridViewPrinter(dgvOrderDetails,
                MyPrintDocument, false, true, "Bill", new Font("Tahoma", 18,
                FontStyle.Bold, GraphicsUnit.Point), Color.Black, true);

            return true;
        }

        private void btnPrintPreview_Click(object sender, EventArgs e)
        {
            if (SetupThePrinting())
            {
                PrintPreviewDialog MyPrintPreviewDialog = new PrintPreviewDialog();
                MyPrintPreviewDialog.Document = MyPrintDocument;
                MyPrintPreviewDialog.ShowDialog();
            }
        }

        private void MyPrintDocument_PrintPage_1(object sender, PrintPageEventArgs e)
        {
            bool more = MyDataGridViewPrinter.DrawDataGridView(e.Graphics);
            if (more == true)
                e.HasMorePages = true;
        }
     }
}


Order Form

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Globalization;

namespace TestAsync
{
    public partial class SQLOrder : Form
    {
        AutoCompleteStringCollection namesCollection = new AutoCompleteStringCollection();
        string strCon = System.Configuration.ConfigurationSettings.AppSettings["connString2"].ToString();
        SqlDataReader dr;
        SqlConnection conn;
        SqlCommand cmd = new SqlCommand();

        DataSet ds = new DataSet();
        DataTable dt = new DataTable();
       
        public SQLOrder()
        {
            InitializeComponent();

            this.txtItems.KeyDown += new KeyEventHandler(txtItems_KeyDown);
            //this.txtSearch.KeyDown += new KeyEventHandler(txtSearch_KeyDown);


            conn = new SqlConnection(strCon);
            //conn.ConnectionString = strCon;
            cmd.Connection = conn;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "select distinct ItemName from zItemMaster order by ItemName";
            conn.Open();
            dr = cmd.ExecuteReader();
            if (dr.HasRows == true)
            {
                while (dr.Read())
                {
                    namesCollection.Add(dr["ItemName"].ToString());
                }
            }
            else
            {
                MessageBox.Show("Data not found");
            }
            dr.Close();
            conn.Close();
            txtItems.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            txtItems.AutoCompleteSource = AutoCompleteSource.CustomSource;
            txtItems.AutoCompleteCustomSource = namesCollection;           
        }

        private void txtItems_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                //if (itemExists())
                //{
                    retPrice();
                    btnAdd.Focus();
                //}
                //else
                //{
                //    MessageBox.Show("Item already in the list.", "Error");
                //}
            }
        }

        private bool IsitemExists()
        {
            int flagFound = 0;

            if (dgvOrderList.Rows.Count == 0)
                return false;
            
            if (dgvOrderList.Rows.Count >= 1)
            {
                for (int i = 0; i < (dgvOrderList.Rows.Count); i++)
                {
                    if (dgvOrderList.Rows[i].Cells["Item"].Value.ToString().ToUpper().Equals(txtItems.Text.ToUpper()))
                    {
                        flagFound++;
                    }
                }
            }
                if (flagFound > 0)
                    return true;
                else
                    return false;
        }

        private void retPrice()
        {
            SqlDataReader dr1;
            cmd.Connection = conn;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "select ItemPrice from zItemMaster where ItemName = '" + txtItems.Text + "'";
            conn.Open();
            dr1 = cmd.ExecuteReader();
            if (dr1.HasRows == true)
            {
                while (dr1.Read())
                {
                    lblCurrentPrice.Text = dr1["ItemPrice"].ToString();
                }
            }
            dr1.Close();
            conn.Close();
        }

        //private void retPrice()
        //{
        //    SqlDataReader dr1;
        //    cmd.Connection = conn;
        //    cmd.CommandType = CommandType.Text;
        //    cmd.CommandText = "select ItemPrice, ItemID from zItemMaster where ItemName = '" + txtItems.Text + "'";
        //    conn.Open();
        //    dr1 = cmd.ExecuteReader();
        //    if (dr1.HasRows == true)
        //    {
        //        while (dr1.Read())
        //        {
        //            lblID.Text = dr1["ItemID"].ToString();
        //            lblCurrentPrice.Text = dr1["ItemPrice"].ToString();
        //        }
        //    }
        //    dr1.Close();
        //    conn.Close();
        //}

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (txtItems.Text != "")
            {
                if (lblCurrentPrice.Text != "" || lblCurrentPrice.Text != "0")
                {
                    if (txtQuantity.Text == "")
                    {
                        if (IsitemExists() == false)
                        {
                            string[] row = new string[] { txtItems.Text, lblCurrentPrice.Text };

                            dgvOrderList.Rows.Add(row);

                            // Insert into Database

                            conn = new SqlConnection(strCon);

                            string strCommand;

                            strCommand = "insert into zTable" + GlobalForms.selectedTable + " (Item, Price)" +
                                         " values ('" + row[0] + "', " + row[1] + ")";
                            conn.Open();
                            //SqlCommand cmd = new SqlCommand(strCommand, conn);
                            cmd.CommandType = CommandType.Text;
                            cmd.CommandText = strCommand;
                            cmd.Connection = conn;

                            cmd.ExecuteNonQuery();
                            conn.Close();

                            //********************
                            lblTotalPrice.Text = "";

                            calculateTotal();

                            txtItems.Clear();
                            lblCurrentPrice.Text = "";
                            txtItems.Focus();
                        }
                        else
                        {
                            MessageBox.Show("Item already in list.");
                            txtItems.Focus();
                            return;
                        }
                    }
                }
                if (txtQuantity.Text != "")
                {
                    if (IsitemExists() == false)
                    {
                        double totPrice = Convert.ToDouble(Convert.ToDouble(lblCurrentPrice.Text) * Convert.ToDouble(txtQuantity.Text));
                        string[] row = new string[] { txtItems.Text, totPrice.ToString() };

                        dgvOrderList.Rows.Add(row);

                        // Insert into Database

                        conn = new SqlConnection(strCon);

                        string strCommand;

                        strCommand = "insert into zTable" + GlobalForms.selectedTable + " (Item, Price)" +
                                     " values ('" + row[0] + "', " + row[1] + ")";
                        conn.Open();
                        //SqlCommand cmd = new SqlCommand(strCommand, conn);
                        cmd.CommandType = CommandType.Text;
                        cmd.CommandText = strCommand;
                        cmd.Connection = conn;

                        cmd.ExecuteNonQuery();
                        conn.Close();

                        //********************
                        lblTotalPrice.Text = "";

                        calculateTotal();

                        txtItems.Clear();
                        lblCurrentPrice.Text = "";
                        txtQuantity.Clear();
                        txtItems.Focus();
                    }
                }
                else
                {
                    MessageBox.Show("Item already in list.");
                    txtItems.Focus();
                    return;
                }
            }
            else
            {
                MessageBox.Show("Please Select the item first.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtItems.Focus();
            }
        }

        private void calculateTotal()
        {
            double sum = 0;

            foreach (DataGridViewRow row in dgvOrderList.Rows)
            {
                sum += Convert.ToDouble(row.Cells[1].Value);
            }

            lblTotalPrice.Text = sum.ToString();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

        private void SQLOrder_Load(object sender, EventArgs e)
        {
            this.Text = GlobalForms.strTableNo;
        }

        private void btnCheckOut_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable emptyDT = new DataTable();
                conn = new SqlConnection(strCon);

                string strCommand;

                strCommand = "truncate table zTable" + GlobalForms.selectedTable;
                conn.Open();
                SqlCommand cmd = new SqlCommand(strCommand, conn);

                cmd.ExecuteNonQuery();
                conn.Close();
                emptyDT.Clear();
                //int tempT = GlobalForms.selectedTable - 1;
                this.dgvOrderList.DataSource = emptyDT;
                this.dgvOrderList.DataSource = null;

                this.Close();
            }
            catch
            { }
        }

        private void dgvOrderList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            // Remove item Database
            if (e.ColumnIndex == 2)
            {
                conn = new SqlConnection(strCon);

                string strCommand;

                strCommand = "DELETE FROM zTable" + GlobalForms.selectedTable +
                             " WHERE Item = '" + dgvOrderList.Rows[e.RowIndex].Cells[0].Value + "'";
                conn.Open();
                //SqlCommand cmd = new SqlCommand(strCommand, conn);
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = strCommand;
                cmd.Connection = conn;

                cmd.ExecuteNonQuery();
                conn.Close();

                //********************

                // Remove from Datagridview List
                dgvOrderList.Rows.RemoveAt(e.RowIndex);
                calculateTotal();
            }
        }

        //private void txtSearch_KeyDown(object sender, KeyEventArgs e)
        //{
        //    if (e.KeyCode == Keys.Enter)
        //    {
        //        dgvOrderList.Rows[0].Selected = false;
        //        for (int i = 0; i < (dgvOrderList.Rows.Count); i++)
        //        {
        //            if (dgvOrderList.Rows[i].Cells["Item"].Value.ToString().StartsWith(txtSearch.Text, true, CultureInfo.InvariantCulture))
        //            {
        //                //dgvOrderList.Rows[i].Cells[0].Selected = true;
                        
        //                dgvOrderList.Rows[i].DefaultCellStyle.BackColor = Color.Blue;
        //                //return; // stop looping
        //            }
        //        }

        //    }
        //}

        private void btnSearch_Click(object sender, EventArgs e)
        {
            for (int j = 0; j < (dgvOrderList.Rows.Count); j++)
            {
                dgvOrderList.Rows[j].Selected = false;
            }

            for (int i = 0; i < (dgvOrderList.Rows.Count); i++)
            {
                if (dgvOrderList.Rows[i].Cells["Item"].Value.ToString().StartsWith(txtItems.Text, true, CultureInfo.InvariantCulture))
                {
                    //dgvOrderList.Rows[i].Cells[0].Selected = true;

                    dgvOrderList.Rows[i].DefaultCellStyle.BackColor = Color.LightPink;
                    //return; // stop looping
                }
                else
                    dgvOrderList.Rows[i].DefaultCellStyle.BackColor = Color.White;
            }
        }

        //private void SQLOrder_FormClosing(object sender, FormClosingEventArgs e)
        //{
        //    SQLMain.tempDT = null;
        //    this.DialogResult = System.Windows.Forms.DialogResult.OK;
        //}
    }
}


MGlobal Class

C#
public static class GlobalForms
    {
        public static OrderForm ordfrm;
        public static string strTableNo;
        public static int selectedTable = 0;
        public static int TotalTables = 5;
    }


Printer Class .cs

C#
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Printing;
using System.Data;
using System.Windows.Forms;

class DataGridViewPrinter
{
    private DataGridView TheDataGridView; // The DataGridView Control which will be printed
    private PrintDocument ThePrintDocument; // The PrintDocument to be used for printing
    private bool IsCenterOnPage; // Determine if the report will be printed in the Top-Center of the page
    private bool IsWithTitle; // Determine if the page contain title text
    private string TheTitleText; // The title text to be printed in each page (if IsWithTitle is set to true)
    private Font TheTitleFont; // The font to be used with the title text (if IsWithTitle is set to true)
    private Color TheTitleColor; // The color to be used with the title text (if IsWithTitle is set to true)
    private bool IsWithPaging; // Determine if paging is used

    static int CurrentRow; // A static parameter that keep track on which Row (in the DataGridView control) that should be printed

    static int PageNumber;

    private int PageWidth;
    private int PageHeight;
    private int LeftMargin;
    private int TopMargin;
    private int RightMargin;
    private int BottomMargin;

    private float CurrentY; // A parameter that keep track on the y coordinate of the page, so the next object to be printed will start from this y coordinate

    private float RowHeaderHeight;
    private List<float> RowsHeight;
    private List<float> ColumnsWidth;
    private float TheDataGridViewWidth;
        
    // Maintain a generic list to hold start/stop points for the column printing
    // This will be used for wrapping in situations where the DataGridView will not fit on a single page
    private List<int[]> mColumnPoints;
    private List<float> mColumnPointsWidth;
    private int mColumnPoint;
        
    // The class constructor
    public DataGridViewPrinter(DataGridView aDataGridView, PrintDocument aPrintDocument, bool CenterOnPage, bool WithTitle, string aTitleText, Font aTitleFont, Color aTitleColor, bool WithPaging)
    {
        TheDataGridView = aDataGridView;
        ThePrintDocument = aPrintDocument;
        IsCenterOnPage = CenterOnPage;
        IsWithTitle = WithTitle;
        TheTitleText = aTitleText;
        TheTitleFont = aTitleFont;
        TheTitleColor = aTitleColor;
        IsWithPaging = WithPaging;

        PageNumber = 0;

        RowsHeight = new List<float>();
        ColumnsWidth = new List<float>();

        mColumnPoints = new List<int[]>();
        mColumnPointsWidth = new List<float>();

        // Claculating the PageWidth and the PageHeight
        if (!ThePrintDocument.DefaultPageSettings.Landscape)
        {
            PageWidth = ThePrintDocument.DefaultPageSettings.PaperSize.Width;
            PageHeight = ThePrintDocument.DefaultPageSettings.PaperSize.Height;
        }
        else
        {
            PageHeight = ThePrintDocument.DefaultPageSettings.PaperSize.Width;
            PageWidth = ThePrintDocument.DefaultPageSettings.PaperSize.Height;
        }

        // Claculating the page margins
        LeftMargin = ThePrintDocument.DefaultPageSettings.Margins.Left;
        TopMargin = ThePrintDocument.DefaultPageSettings.Margins.Top;
        RightMargin = ThePrintDocument.DefaultPageSettings.Margins.Right;
        BottomMargin = ThePrintDocument.DefaultPageSettings.Margins.Bottom;

        // First, the current row to be printed is the first row in the DataGridView control
        CurrentRow = 0;
    }

    // The function that calculate the height of each row (including the header row), the width of each column (according to the longest text in all its cells including the header cell), and the whole DataGridView width
    private void Calculate(Graphics g)
    {
        if (PageNumber == 0) // Just calculate once
        {
            SizeF tmpSize = new SizeF();
            Font tmpFont;
            float tmpWidth;

            TheDataGridViewWidth = 0;
            for (int i = 0; i < TheDataGridView.Columns.Count; i++)
            {
                tmpFont = TheDataGridView.ColumnHeadersDefaultCellStyle.Font;
                if (tmpFont == null) // If there is no special HeaderFont style, then use the default DataGridView font style
                    tmpFont = TheDataGridView.DefaultCellStyle.Font;

                tmpSize = g.MeasureString(TheDataGridView.Columns[i].HeaderText, tmpFont);
                tmpWidth = tmpSize.Width;
                RowHeaderHeight = tmpSize.Height;

                for (int j = 0; j < TheDataGridView.Rows.Count; j++)
                {
                    tmpFont = TheDataGridView.Rows[j].DefaultCellStyle.Font;
                    if (tmpFont == null) // If the there is no special font style of the CurrentRow, then use the default one associated with the DataGridView control
                        tmpFont = TheDataGridView.DefaultCellStyle.Font;

                    tmpSize = g.MeasureString("Anything", tmpFont);
                    RowsHeight.Add(tmpSize.Height);

                    tmpSize = g.MeasureString(TheDataGridView.Rows[j].Cells[i].EditedFormattedValue.ToString(), tmpFont);
                    if (tmpSize.Width > tmpWidth)
                        tmpWidth = tmpSize.Width;
                }
                if (TheDataGridView.Columns[i].Visible)
                    TheDataGridViewWidth += tmpWidth;
                ColumnsWidth.Add(tmpWidth);
            }

            // Define the start/stop column points based on the page width and the DataGridView Width
            // We will use this to determine the columns which are drawn on each page and how wrapping will be handled
            // By default, the wrapping will occurr such that the maximum number of columns for a page will be determine
            int k;

            int mStartPoint = 0;
            for (k = 0; k < TheDataGridView.Columns.Count; k++)
                if (TheDataGridView.Columns[k].Visible)
                {
                    mStartPoint = k;
                    break;
                }

            int mEndPoint = TheDataGridView.Columns.Count;
            for (k = TheDataGridView.Columns.Count - 1; k >= 0; k--)
                if (TheDataGridView.Columns[k].Visible)
                {
                    mEndPoint = k + 1;
                    break;
                }

            float mTempWidth = TheDataGridViewWidth;
            float mTempPrintArea = (float)PageWidth - (float)LeftMargin - (float)RightMargin;
            
            // We only care about handling where the total datagridview width is bigger then the print area
            if (TheDataGridViewWidth > mTempPrintArea)
            {
                mTempWidth = 0.0F;
                for (k = 0; k < TheDataGridView.Columns.Count; k++)
                {
                    if (TheDataGridView.Columns[k].Visible)
                    {
                        mTempWidth += ColumnsWidth[k];
                        // If the width is bigger than the page area, then define a new column print range
                        if (mTempWidth > mTempPrintArea)
                        {
                            mTempWidth -= ColumnsWidth[k];
                            mColumnPoints.Add(new int[] { mStartPoint, mEndPoint });
                            mColumnPointsWidth.Add(mTempWidth);
                            mStartPoint = k;
                            mTempWidth = ColumnsWidth[k];
                        }
                    }
                    // Our end point is actually one index above the current index
                    mEndPoint = k + 1;
                }
            }
            // Add the last set of columns
            mColumnPoints.Add(new int[] { mStartPoint, mEndPoint });
            mColumnPointsWidth.Add(mTempWidth);
            mColumnPoint = 0;
        }
    }

    // The funtion that print the title, page number, and the header row
    private void DrawHeader(Graphics g)
    {
        CurrentY = (float)TopMargin;

        // Printing the page number (if isWithPaging is set to true)
        if (IsWithPaging)
        {
            PageNumber++;
            string PageString = "Page " + PageNumber.ToString();

            StringFormat PageStringFormat = new StringFormat();
            PageStringFormat.Trimming = StringTrimming.Word;
            PageStringFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip;
            PageStringFormat.Alignment = StringAlignment.Far;

            Font PageStringFont = new Font("Tahoma", 8, FontStyle.Regular, GraphicsUnit.Point);

            RectangleF PageStringRectangle = new RectangleF((float)LeftMargin, CurrentY, (float)PageWidth - (float)RightMargin - (float)LeftMargin, g.MeasureString(PageString, PageStringFont).Height);

            g.DrawString(PageString, PageStringFont, new SolidBrush(Color.Black), PageStringRectangle, PageStringFormat);

            CurrentY += g.MeasureString(PageString, PageStringFont).Height;
        }

        // Printing the title (if IsWithTitle is set to true)
        if (IsWithTitle)
        {
            StringFormat TitleFormat = new StringFormat();
            TitleFormat.Trimming = StringTrimming.Word;
            TitleFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip;
            if (IsCenterOnPage)
                TitleFormat.Alignment = StringAlignment.Center;
            else
                TitleFormat.Alignment = StringAlignment.Near;

            RectangleF TitleRectangle = new RectangleF((float)LeftMargin, CurrentY, (float)PageWidth - (float)RightMargin - (float)LeftMargin, g.MeasureString(TheTitleText, TheTitleFont).Height);

            g.DrawString(TheTitleText, TheTitleFont, new SolidBrush(TheTitleColor), TitleRectangle, TitleFormat);

            CurrentY += g.MeasureString(TheTitleText, TheTitleFont).Height;
        }

        // Calculating the starting x coordinate that the printing process will start from
        float CurrentX = (float)LeftMargin;
        if (IsCenterOnPage)            
            CurrentX += (((float)PageWidth - (float)RightMargin - (float)LeftMargin) - mColumnPointsWidth[mColumnPoint]) / 2.0F;

        // Setting the HeaderFore style
        Color HeaderForeColor = TheDataGridView.ColumnHeadersDefaultCellStyle.ForeColor;
        if (HeaderForeColor.IsEmpty) // If there is no special HeaderFore style, then use the default DataGridView style
            HeaderForeColor = TheDataGridView.DefaultCellStyle.ForeColor;
        SolidBrush HeaderForeBrush = new SolidBrush(HeaderForeColor);

        // Setting the HeaderBack style
        
        // Edited by Prafull START
        Color HeaderBackColor = Color.White;// TheDataGridView.ColumnHeadersDefaultCellStyle.BackColor;
        // Edited by Prafull END

        if (HeaderBackColor.IsEmpty) // If there is no special HeaderBack style, then use the default DataGridView style
            HeaderBackColor = TheDataGridView.DefaultCellStyle.BackColor;
        SolidBrush HeaderBackBrush = new SolidBrush(HeaderBackColor);

        // Setting the LinePen that will be used to draw lines and rectangles (derived from the GridColor property of the DataGridView control)
        
        // Edited by Prafull START
        //Pen TheLinePen = new Pen(TheDataGridView.GridColor, 1);
        Pen TheLinePen = new Pen(Color.White);
        // Edited by Prafull END

        // Setting the HeaderFont style
        Font HeaderFont = TheDataGridView.ColumnHeadersDefaultCellStyle.Font;
        if (HeaderFont == null) // If there is no special HeaderFont style, then use the default DataGridView font style
            HeaderFont = TheDataGridView.DefaultCellStyle.Font;

        // Calculating and drawing the HeaderBounds        
        RectangleF HeaderBounds = new RectangleF(CurrentX, CurrentY, mColumnPointsWidth[mColumnPoint], RowHeaderHeight);
        g.FillRectangle(HeaderBackBrush, HeaderBounds);

        // Setting the format that will be used to print each cell of the header row
        StringFormat CellFormat = new StringFormat();
        CellFormat.Trimming = StringTrimming.Word;
        CellFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip;

        // Printing each visible cell of the header row
        RectangleF CellBounds;
        float ColumnWidth;        
        for (int i = (int)mColumnPoints[mColumnPoint].GetValue(0); i < (int)mColumnPoints[mColumnPoint].GetValue(1); i++)
        {
            if (!TheDataGridView.Columns[i].Visible) continue; // If the column is not visible then ignore this iteration

            ColumnWidth = ColumnsWidth[i];

            // Check the CurrentCell alignment and apply it to the CellFormat
            if (TheDataGridView.ColumnHeadersDefaultCellStyle.Alignment.ToString().Contains("Right"))
                CellFormat.Alignment = StringAlignment.Far;
            else if (TheDataGridView.ColumnHeadersDefaultCellStyle.Alignment.ToString().Contains("Center"))
                CellFormat.Alignment = StringAlignment.Center;
            else
                CellFormat.Alignment = StringAlignment.Near;

            CellBounds = new RectangleF(CurrentX, CurrentY, ColumnWidth, RowHeaderHeight);

            // Printing the cell text
            g.DrawString(TheDataGridView.Columns[i].HeaderText, HeaderFont, HeaderForeBrush, CellBounds, CellFormat);

            // Drawing the cell bounds
            if (TheDataGridView.RowHeadersBorderStyle != DataGridViewHeaderBorderStyle.None) // Draw the cell border only if the HeaderBorderStyle is not None
                g.DrawRectangle(TheLinePen, CurrentX, CurrentY, ColumnWidth, RowHeaderHeight);

            CurrentX += ColumnWidth;
        }

        // Edited by Prafull START
        // To add new blank row after header text
        CurrentY += RowHeaderHeight + 10;
        // Edited by Prafull END
        
    }

    // The function that print a bunch of rows that fit in one page
    // When it returns true, meaning that there are more rows still not printed, so another PagePrint action is required
    // When it returns false, meaning that all rows are printed (the CureentRow parameter reaches the last row of the DataGridView control) and no further PagePrint action is required
    private bool DrawRows(Graphics g)
    {
        // Setting the LinePen that will be used to draw lines and rectangles (derived from the GridColor property of the DataGridView control)
        //Pen TheLinePen = new Pen(TheDataGridView.GridColor, 1);
        Pen TheLinePen = new Pen(Color.White);

        // The style paramters that will be used to print each cell
        Font RowFont;
        Color RowForeColor;
        Color RowBackColor;
        SolidBrush RowForeBrush;
        SolidBrush RowBackBrush;
        SolidBrush RowAlternatingBackBrush;

        // Setting the format that will be used to print each cell
        StringFormat CellFormat = new StringFormat();
        CellFormat.Trimming = StringTrimming.Word;
        CellFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit;

        // Printing each visible cell
        RectangleF RowBounds;
        float CurrentX;
        float ColumnWidth;
        while (CurrentRow < TheDataGridView.Rows.Count)
        {
            if (TheDataGridView.Rows[CurrentRow].Visible) // Print the cells of the CurrentRow only if that row is visible
            {
                // Setting the row font style
                RowFont = TheDataGridView.Rows[CurrentRow].DefaultCellStyle.Font;
                if (RowFont == null) // If the there is no special font style of the CurrentRow, then use the default one associated with the DataGridView control
                    RowFont = TheDataGridView.DefaultCellStyle.Font;

                // Setting the RowFore style
                RowForeColor = TheDataGridView.Rows[CurrentRow].DefaultCellStyle.ForeColor;
                if (RowForeColor.IsEmpty) // If the there is no special RowFore style of the CurrentRow, then use the default one associated with the DataGridView control
                    RowForeColor = TheDataGridView.DefaultCellStyle.ForeColor;
                RowForeBrush = new SolidBrush(RowForeColor);

                // Setting the RowBack (for even rows) and the RowAlternatingBack (for odd rows) styles
                RowBackColor = TheDataGridView.Rows[CurrentRow].DefaultCellStyle.BackColor;
                if (RowBackColor.IsEmpty) // If the there is no special RowBack style of the CurrentRow, then use the default one associated with the DataGridView control
                {
                    RowBackBrush = new SolidBrush(TheDataGridView.DefaultCellStyle.BackColor);
                    RowAlternatingBackBrush = new SolidBrush(TheDataGridView.AlternatingRowsDefaultCellStyle.BackColor);
                }
                else // If the there is a special RowBack style of the CurrentRow, then use it for both the RowBack and the RowAlternatingBack styles
                {
                    RowBackBrush = new SolidBrush(RowBackColor);
                    RowAlternatingBackBrush = new SolidBrush(RowBackColor);
                }

                // Calculating the starting x coordinate that the printing process will start from
                CurrentX = (float)LeftMargin;
                if (IsCenterOnPage)                    
                    CurrentX += (((float)PageWidth - (float)RightMargin - (float)LeftMargin) - mColumnPointsWidth[mColumnPoint]) / 2.0F;

                // Calculating the entire CurrentRow bounds                
                RowBounds = new RectangleF(CurrentX, CurrentY, mColumnPointsWidth[mColumnPoint], RowsHeight[CurrentRow]);

                // Filling the back of the CurrentRow
                if (CurrentRow % 2 == 0)
                    g.FillRectangle(RowBackBrush, RowBounds);
                else
                    g.FillRectangle(RowAlternatingBackBrush, RowBounds);

                // Printing each visible cell of the CurrentRow                
                for (int CurrentCell = (int)mColumnPoints[mColumnPoint].GetValue(0); CurrentCell < (int)mColumnPoints[mColumnPoint].GetValue(1); CurrentCell++)
                {
                    if (!TheDataGridView.Columns[CurrentCell].Visible) continue; // If the cell is belong to invisible column, then ignore this iteration

                    // Check the CurrentCell alignment and apply it to the CellFormat
                    if (TheDataGridView.Columns[CurrentCell].DefaultCellStyle.Alignment.ToString().Contains("Right"))
                        CellFormat.Alignment = StringAlignment.Far;
                    else if (TheDataGridView.Columns[CurrentCell].DefaultCellStyle.Alignment.ToString().Contains("Center"))
                        CellFormat.Alignment = StringAlignment.Center;
                    else
                        CellFormat.Alignment = StringAlignment.Near;
                    
                    ColumnWidth = ColumnsWidth[CurrentCell];
                    RectangleF CellBounds = new RectangleF(CurrentX, CurrentY, ColumnWidth, RowsHeight[CurrentRow]);

                    // Printing the cell text
                    g.DrawString(TheDataGridView.Rows[CurrentRow].Cells[CurrentCell].EditedFormattedValue.ToString(), RowFont, RowForeBrush, CellBounds, CellFormat);
                    
                    // Drawing the cell bounds
                    if (TheDataGridView.CellBorderStyle != DataGridViewCellBorderStyle.None) // Draw the cell border only if the CellBorderStyle is not None
                        g.DrawRectangle(TheLinePen, CurrentX, CurrentY, ColumnWidth, RowsHeight[CurrentRow]);

                    CurrentX += ColumnWidth;
                }
                CurrentY += RowsHeight[CurrentRow];

                // Checking if the CurrentY is exceeds the page boundries
                // If so then exit the function and returning true meaning another PagePrint action is required
                if ((int)CurrentY > (PageHeight - TopMargin - BottomMargin))
                {
                    CurrentRow++;
                    return true;
                }
            }
            CurrentRow++;
        }

        CurrentRow = 0;
        mColumnPoint++; // Continue to print the next group of columns

        if (mColumnPoint == mColumnPoints.Count) // Which means all columns are printed
        {
            mColumnPoint = 0;
            return false;
        }
        else
            return true;
    }

    // The method that calls all other functions
    public bool DrawDataGridView(Graphics g)
    {
        try
        {
            Calculate(g);
            DrawHeader(g);
            bool bContinue = DrawRows(g);
            return bContinue;
        }
        catch (Exception ex)
        {
            MessageBox.Show("Operation failed: " + ex.Message.ToString(), Application.ProductName + " - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return false;
        }
    }
}

GeneralRe: Nice Article Pin
Prafull_neo_code21-Jan-12 1:50
Prafull_neo_code21-Jan-12 1:50 
GeneralRe: Nice Article Pin
Prafull_neo_code23-Jan-12 1:31
Prafull_neo_code23-Jan-12 1:31 
GeneralRe: Nice Article Pin
Prafull_neo_code23-Jan-12 4:30
Prafull_neo_code23-Jan-12 4:30 
GeneralRe: Nice Article Pin
Prafull_neo_code28-Jan-12 3:20
Prafull_neo_code28-Jan-12 3:20 
Questioni don't want to use a command bar but... Pin
Dimeac22-Sep-07 5:05
Dimeac22-Sep-07 5:05 
Generalgood Pin
vikas amin23-Aug-05 1:01
vikas amin23-Aug-05 1:01 
GeneralRe: good Pin
Rick Pingry23-Aug-05 4:42
Rick Pingry23-Aug-05 4:42 
GeneralCool! Pin
Jörgen Sigvardsson6-Jul-05 8:47
Jörgen Sigvardsson6-Jul-05 8:47 
Questionhow to lock pane for auto-resizing ? Pin
Mandalay17-Jul-04 2:48
Mandalay17-Jul-04 2:48 
AnswerRe: how to lock pane for auto-resizing ? Pin
Mandalay18-Jul-04 0:40
Mandalay18-Jul-04 0:40 
GeneralScroll Bars in Dialog Box Pin
Rick Pingry3-Apr-04 3:58
Rick Pingry3-Apr-04 3:58 
QuestionMiss atlres.h? Pin
tsung-yu25-Dec-03 20:53
tsung-yu25-Dec-03 20:53 
AnswerRe: Miss atlres.h? Pin
dragon wang29-Dec-03 3:57
dragon wang29-Dec-03 3:57 
GeneralRe: Miss atlres.h? Pin
Member 21272217-Apr-05 23:07
Member 21272217-Apr-05 23:07 
GeneralCrashes on New File Pin
jweston30-Jun-03 4:49
jweston30-Jun-03 4:49 
GeneralRe: Crashes on New File Pin
Ed Gadziemski30-Jun-03 9:15
professionalEd Gadziemski30-Jun-03 9:15 
GeneralRe: Crashes on New File Pin
jweston1-Jul-03 2:46
jweston1-Jul-03 2:46 
GeneralRe: Crashes on New File Pin
jweston29-Jul-03 2:47
jweston29-Jul-03 2:47 
GeneralRe: Crashes on New File Pin
fioresoft28-Jul-03 18:09
fioresoft28-Jul-03 18:09 
GeneralRe: Crashes on New File Pin
e-buch29-Sep-04 23:25
e-buch29-Sep-04 23:25 
GeneralRe: Crashes on New File Pin
free2000fly13-Nov-07 4:06
free2000fly13-Nov-07 4:06 
GeneralChanging the panes around Pin
jasco14-Dec-02 12:46
jasco14-Dec-02 12:46 
QuestionMFC MDI Application with Splitter? Pin
jasco7-Dec-02 12:49
jasco7-Dec-02 12:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.