Click here to Skip to main content
13,667,062 members
Click here to Skip to main content
Add your own
alternative version

Stats

47.1K views
3.5K downloads
74 bookmarked
Posted 23 Jan 2015
Licenced CPOL

DataGridView Helper Class

, 23 Jan 2015
Rate this:
Please Sign up or sign in to vote.
DataGridView Helper Class for Winforms

Introduction

In this article I will explain about how to create a Helper Class for DataGridView in Winform Application. In one of my web project I want to create the datagridview Dynamically at runtime. When i start my project I was looking for a Helper Class for DataGridView and used Google for get one Helper Class. But i couldn’t found any helper class for DataGridView. So I plan to create a Helper Class for DataGridView. As a result I have created a helper class for DataGridView. I want to share my helper class with others so that they can use my class in there project and make a code simple and easy.

WHY WE NEED HELPER CLASS:

  • Helper Class will make our code part Simple and Standard.
  • All the Events of DataGridview can be defined in the helperClass . In our form we can call the method from helper class and make our code simple.
  • One Time Design in Class can be used for the whole project.
  • This will be useful if we change design only in Class File and no need to redesign in each form.

WHAT WE HAVE IN HELPER CLASS:

  • Design your Datagridview ,Add the Datagridview to your controls like Panel,Tab or in your form.
  • Bound Column
  • CheckBox Column
  • TextBox Column
  • Numeric TextBox Column
  • ComboBox Column
  • DateTimePicker Column
  • Button Column
  • Colour Dialog Column
  • DataGridView Events like CellClick,CellContentClick and etc.

Here is an sample with Color Dialog from button Column.

Using the code

First we can start with the helper class and then we can see how to use the helper class in Winform. In my helper class I have the fallowing function to make the design and bind simple.

  • Layout
  • Generategrid
  • Templatecolumn
  • NumeriTextboxEvents
  • DateTimePickerEvents
  • DGVClickEvents
  • colorDialogEvents

We can see few important functions of the class and then i will paste my full class Code here.

Layout: This method will be setting the BackgroundColor, BackColor,AllowUserToAddRows and etc for the datagridView. In this method we pass our Datagridview and setting all the design part for grid.

//Set all the DGV layout
      #region Layout

      public static void Layouts(DataGridView ShanuDGV, Color BackgroundColor, Color RowsBackColor, Color AlternatebackColor, Boolean AutoGenerateColumns, Color HeaderColor, Boolean HeaderVisual, Boolean RowHeadersVisible, Boolean AllowUserToAddRows)
      {
          //Grid Back ground Color
          ShanuDGV.BackgroundColor = BackgroundColor;

          //Grid Back Color
          ShanuDGV.RowsDefaultCellStyle.BackColor = RowsBackColor;

          //GridColumnStylesCollection Alternate Rows Backcolr
          ShanuDGV.AlternatingRowsDefaultCellStyle.BackColor = AlternatebackColor;

          // Auto generated here set to tru or false.
          ShanuDGV.AutoGenerateColumns = AutoGenerateColumns;
        //  ShanuDGV.DefaultCellStyle.Font = new Font("Verdana", 10.25f, FontStyle.Regular);
         // ShanuDGV.ColumnHeadersDefaultCellStyle.Font = new Font("Calibri", 11, FontStyle.Regular);

          //Column Header back Color
          ShanuDGV.ColumnHeadersDefaultCellStyle.BackColor = HeaderColor;

          //header Visisble
          ShanuDGV.EnableHeadersVisualStyles = HeaderVisual;

          // Enable the row header
          ShanuDGV.RowHeadersVisible = RowHeadersVisible;

          // to Hide the Last Empty row here we use false.
          ShanuDGV.AllowUserToAddRows = AllowUserToAddRows;
      }
      #endregion

Generategrid: In this method we pass our Datagridview and set the height,width,position and bind the datagriview to our selected control.

public static void Generategrid(DataGridView ShanuDGV, Control cntrlName, int width, int height, int xval, int yval)
       {
           ShanuDGV.Location = new Point(xval, yval);
           ShanuDGV.Size = new Size(width, height);
           //ShanuDGV.Dock = docktyope.
           cntrlName.Controls.Add(ShanuDGV);
       }

TemplateColumn: This is the important method in the helperclass,Here we pass the Datagriview and define the column as Bound ,Checkbox,Textbox DateTimePicker and etc.Here we set each column width, Alignment, Visibility, BackColor,Font Color and etc.

public static void Templatecolumn(DataGridView ShanuDGV, ShanuControlTypes ShanuControlTypes, String cntrlnames, String Headertext, String ToolTipText, Boolean Visible, int width, DataGridViewTriState Resizable, DataGridViewContentAlignment cellAlignment, DataGridViewContentAlignment headerAlignment, Color CellTemplateBackColor, DataTable dtsource, String DisplayMember, String ValueMember, Color CellTemplateforeColor)
        {
            switch (ShanuControlTypes)
            {
                case ShanuControlTypes.CheckBox:
                      DataGridViewCheckBoxColumn dgvChk = new DataGridViewCheckBoxColumn();
                        dgvChk.ValueType = typeof(bool);
                        dgvChk.Name = cntrlnames;
                      
                        dgvChk.HeaderText = Headertext;
                        dgvChk.ToolTipText = ToolTipText;
                        dgvChk.Visible = Visible;
                        dgvChk.Width = width;
                        dgvChk.SortMode = DataGridViewColumnSortMode.Automatic;
                        dgvChk.Resizable = Resizable;
                        dgvChk.DefaultCellStyle.Alignment = cellAlignment;
                        dgvChk.HeaderCell.Style.Alignment = headerAlignment;
                        if (CellTemplateBackColor.Name.ToString() != "Transparent")
                        {
                            dgvChk.CellTemplate.Style.BackColor = CellTemplateBackColor;
                        }
                        dgvChk.DefaultCellStyle.ForeColor = CellTemplateforeColor;  
                        ShanuDGV.Columns.Add(dgvChk);
                    break;
                case ShanuControlTypes.BoundColumn:
                   DataGridViewColumn col = new DataGridViewTextBoxColumn();
                       col.DataPropertyName = cntrlnames;
                       col.Name = cntrlnames;
                       col.HeaderText = Headertext;
                       col.ToolTipText = ToolTipText;
                       col.Visible = Visible;
                       col.Width = width;
                       col.SortMode = DataGridViewColumnSortMode.Automatic;
                       col.Resizable = Resizable;
                       col.DefaultCellStyle.Alignment = cellAlignment;
                       col.HeaderCell.Style.Alignment = headerAlignment;
                       if (CellTemplateBackColor.Name.ToString() != "Transparent")
                       {
                           col.CellTemplate.Style.BackColor = CellTemplateBackColor;
                       }
                       col.DefaultCellStyle.ForeColor = CellTemplateforeColor;     
                        ShanuDGV.Columns.Add(col);
                    break;
                case ShanuControlTypes.TextBox:
                    DataGridViewTextBoxColumn dgvText = new DataGridViewTextBoxColumn();
                         dgvText.ValueType = typeof(decimal);
                         dgvText.DataPropertyName = cntrlnames;
                         dgvText.Name = cntrlnames;
                         dgvText.HeaderText = Headertext;
                         dgvText.ToolTipText = ToolTipText;
                         dgvText.Visible = Visible;
                         dgvText.Width = width;
                         dgvText.SortMode = DataGridViewColumnSortMode.Automatic;
                         dgvText.Resizable = Resizable;
                         dgvText.DefaultCellStyle.Alignment = cellAlignment;
                         dgvText.HeaderCell.Style.Alignment = headerAlignment;
                         if (CellTemplateBackColor.Name.ToString() != "Transparent")
                         {
                             dgvText.CellTemplate.Style.BackColor = CellTemplateBackColor;
                         }
                         dgvText.DefaultCellStyle.ForeColor = CellTemplateforeColor;     
                         ShanuDGV.Columns.Add(dgvText);
                    break;
                case ShanuControlTypes.ComboBox:
                    DataGridViewComboBoxColumn dgvcombo = new DataGridViewComboBoxColumn();
                            dgvcombo.ValueType = typeof(decimal);
                            dgvcombo.Name = cntrlnames;
                            dgvcombo.DataSource = dtsource;
                            dgvcombo.DisplayMember = DisplayMember;
                            dgvcombo.ValueMember = ValueMember;
                            dgvcombo.Visible = Visible;
                            dgvcombo.Width = width;
                            dgvcombo.SortMode = DataGridViewColumnSortMode.Automatic;
                            dgvcombo.Resizable = Resizable;
                            dgvcombo.DefaultCellStyle.Alignment = cellAlignment;
                            dgvcombo.HeaderCell.Style.Alignment = headerAlignment;
                            if (CellTemplateBackColor.Name.ToString() != "Transparent")
                            {
                                dgvcombo.CellTemplate.Style.BackColor = CellTemplateBackColor;
                              
                            }
                            dgvcombo.DefaultCellStyle.ForeColor = CellTemplateforeColor;     
                            ShanuDGV.Columns.Add(dgvcombo);
                    break;

                case ShanuControlTypes.Button:
                    DataGridViewButtonColumn dgvButtons = new DataGridViewButtonColumn();
                    dgvButtons.Name = cntrlnames;
                    dgvButtons.FlatStyle = FlatStyle.Popup;
                    dgvButtons.DataPropertyName = cntrlnames;
                    dgvButtons.Visible = Visible;
                    dgvButtons.Width = width;
                    dgvButtons.SortMode = DataGridViewColumnSortMode.Automatic;
                    dgvButtons.Resizable = Resizable;
                    dgvButtons.DefaultCellStyle.Alignment = cellAlignment;
                    dgvButtons.HeaderCell.Style.Alignment = headerAlignment;
                    if (CellTemplateBackColor.Name.ToString() != "Transparent")
                    {
                        dgvButtons.CellTemplate.Style.BackColor = CellTemplateBackColor;
                    }
                    dgvButtons.DefaultCellStyle.ForeColor = CellTemplateforeColor;
                    ShanuDGV.Columns.Add(dgvButtons);
                    break;
            }    
        }

NumerictextBoxEvent: In this method we pass the Datagridview and list of ColumnIndex which need to be set as NumbericTextbox Column.Using the EditingControlShowing Event of Gridview ,I check for all the columns which need to be accept only numbers from the textbox.

 public  void NumeriTextboxEvents(DataGridView ShanuDGV,List<int> columnIndexs)
        {        

            shanuDGVs = ShanuDGV;
            listcolumnIndex=columnIndexs;

            ShanuDGV.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dShanuDGV_EditingControlShowing);
        }
        // grid Editing Control Showing
        private void dShanuDGV_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            e.Control.KeyPress -= new KeyPressEventHandler(itemID_KeyPress);//This line of code resolved my issue
            if (listcolumnIndex.Contains(shanuDGVs.CurrentCell.ColumnIndex))
            {
                TextBox itemID = e.Control as TextBox;
                if (itemID != null)
                {
                    itemID.KeyPress += new KeyPressEventHandler(itemID_KeyPress);
                }
            }
        }
        //Grid Kyey press event
        private void itemID_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar)
                && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }
</int>

DatagridView helperClass Full Source Code :  Here is the full source code of the Datagridview helper class. I have created all the necessary methods which need to be used. if user need more functions they can add those functions as well here in this class and use in your projects.

 class ShanuDGVHelper
    {
        #region Variables
        public DataGridView shanuDGVs = new DataGridView();
       List<int> listcolumnIndex;
        int DateColumnIndex=0;
        int ColorColumnIndex = 0;
        int ClickColumnIndex = 0;
       DateTimePicker shanuDateTimePicker;
       String EventFucntions;
        # endregion

        //Set all the Grid layout
        #region Layout
        
        public static void Layouts(DataGridView ShanuDGV, Color BackgroundColor, Color RowsBackColor, Color AlternatebackColor, Boolean AutoGenerateColumns, Color HeaderColor, Boolean HeaderVisual, Boolean RowHeadersVisible, Boolean AllowUserToAddRows)
        {
            //Grid Back ground Color
            ShanuDGV.BackgroundColor = BackgroundColor;

            //Grid Back Color
            ShanuDGV.RowsDefaultCellStyle.BackColor = RowsBackColor;

            //GridColumnStylesCollection Alternate Rows Backcolr
            ShanuDGV.AlternatingRowsDefaultCellStyle.BackColor = AlternatebackColor;

            // Auto generated here set to tru or false.
            ShanuDGV.AutoGenerateColumns = AutoGenerateColumns;
          //  ShanuDGV.DefaultCellStyle.Font = new Font("Verdana", 10.25f, FontStyle.Regular);
           // ShanuDGV.ColumnHeadersDefaultCellStyle.Font = new Font("Calibri", 11, FontStyle.Regular);

            //Column Header back Color
            ShanuDGV.ColumnHeadersDefaultCellStyle.BackColor = HeaderColor;

            //header Visisble
            ShanuDGV.EnableHeadersVisualStyles = HeaderVisual;
            
            // Enable the row header
            ShanuDGV.RowHeadersVisible = RowHeadersVisible;

            // to Hide the Last Empty row here we use false.
            ShanuDGV.AllowUserToAddRows = AllowUserToAddRows;
        }
        #endregion

        //Add your grid to your selected Control and set height,width,position of your grid.
        #region Variables
        public static void Generategrid(DataGridView ShanuDGV, Control cntrlName, int width, int height, int xval, int yval)
        {
            ShanuDGV.Location = new Point(xval, yval);
            ShanuDGV.Size = new Size(width, height);
            //ShanuDGV.Dock = docktyope.
            cntrlName.Controls.Add(ShanuDGV);
        }
        #endregion

        //Template Column In this column we can add Textbox,Lable,Check Box,Dropdown box and etc
        #region Templatecolumn
        public static void Templatecolumn(DataGridView ShanuDGV, ShanuControlTypes ShanuControlTypes, String cntrlnames, String Headertext, String ToolTipText, Boolean Visible, int width, DataGridViewTriState Resizable, DataGridViewContentAlignment cellAlignment, DataGridViewContentAlignment headerAlignment, Color CellTemplateBackColor, DataTable dtsource, String DisplayMember, String ValueMember, Color CellTemplateforeColor)
        {
            switch (ShanuControlTypes)
            {
                case ShanuControlTypes.CheckBox:
                      DataGridViewCheckBoxColumn dgvChk = new DataGridViewCheckBoxColumn();
                        dgvChk.ValueType = typeof(bool);
                        dgvChk.Name = cntrlnames;
                      
                        dgvChk.HeaderText = Headertext;
                        dgvChk.ToolTipText = ToolTipText;
                        dgvChk.Visible = Visible;
                        dgvChk.Width = width;
                        dgvChk.SortMode = DataGridViewColumnSortMode.Automatic;
                        dgvChk.Resizable = Resizable;
                        dgvChk.DefaultCellStyle.Alignment = cellAlignment;
                        dgvChk.HeaderCell.Style.Alignment = headerAlignment;
                        if (CellTemplateBackColor.Name.ToString() != "Transparent")
                        {
                            dgvChk.CellTemplate.Style.BackColor = CellTemplateBackColor;
                        }
                        dgvChk.DefaultCellStyle.ForeColor = CellTemplateforeColor;  
                        ShanuDGV.Columns.Add(dgvChk);
                    break;
                case ShanuControlTypes.BoundColumn:
                   DataGridViewColumn col = new DataGridViewTextBoxColumn();
                       col.DataPropertyName = cntrlnames;
                       col.Name = cntrlnames;
                       col.HeaderText = Headertext;
                       col.ToolTipText = ToolTipText;
                       col.Visible = Visible;
                       col.Width = width;
                       col.SortMode = DataGridViewColumnSortMode.Automatic;
                       col.Resizable = Resizable;
                       col.DefaultCellStyle.Alignment = cellAlignment;
                       col.HeaderCell.Style.Alignment = headerAlignment;
                       if (CellTemplateBackColor.Name.ToString() != "Transparent")
                       {
                           col.CellTemplate.Style.BackColor = CellTemplateBackColor;
                       }
                       col.DefaultCellStyle.ForeColor = CellTemplateforeColor;     
                        ShanuDGV.Columns.Add(col);
                    break;
                case ShanuControlTypes.TextBox:
                    DataGridViewTextBoxColumn dgvText = new DataGridViewTextBoxColumn();
                         dgvText.ValueType = typeof(decimal);
                         dgvText.DataPropertyName = cntrlnames;
                         dgvText.Name = cntrlnames;
                         dgvText.HeaderText = Headertext;
                         dgvText.ToolTipText = ToolTipText;
                         dgvText.Visible = Visible;
                         dgvText.Width = width;
                         dgvText.SortMode = DataGridViewColumnSortMode.Automatic;
                         dgvText.Resizable = Resizable;
                         dgvText.DefaultCellStyle.Alignment = cellAlignment;
                         dgvText.HeaderCell.Style.Alignment = headerAlignment;
                         if (CellTemplateBackColor.Name.ToString() != "Transparent")
                         {
                             dgvText.CellTemplate.Style.BackColor = CellTemplateBackColor;
                         }
                         dgvText.DefaultCellStyle.ForeColor = CellTemplateforeColor;     
                         ShanuDGV.Columns.Add(dgvText);
                    break;
                case ShanuControlTypes.ComboBox:
                    DataGridViewComboBoxColumn dgvcombo = new DataGridViewComboBoxColumn();
                            dgvcombo.ValueType = typeof(decimal);
                            dgvcombo.Name = cntrlnames;
                            dgvcombo.DataSource = dtsource;
                            dgvcombo.DisplayMember = DisplayMember;
                            dgvcombo.ValueMember = ValueMember;
                            dgvcombo.Visible = Visible;
                            dgvcombo.Width = width;
                            dgvcombo.SortMode = DataGridViewColumnSortMode.Automatic;
                            dgvcombo.Resizable = Resizable;
                            dgvcombo.DefaultCellStyle.Alignment = cellAlignment;
                            dgvcombo.HeaderCell.Style.Alignment = headerAlignment;
                            if (CellTemplateBackColor.Name.ToString() != "Transparent")
                            {
                                dgvcombo.CellTemplate.Style.BackColor = CellTemplateBackColor;
                              
                            }
                            dgvcombo.DefaultCellStyle.ForeColor = CellTemplateforeColor;     
                            ShanuDGV.Columns.Add(dgvcombo);
                    break;

                case ShanuControlTypes.Button:
                    DataGridViewButtonColumn dgvButtons = new DataGridViewButtonColumn();
                    dgvButtons.Name = cntrlnames;
                    dgvButtons.FlatStyle = FlatStyle.Popup;
                    dgvButtons.DataPropertyName = cntrlnames;
                    dgvButtons.Visible = Visible;
                    dgvButtons.Width = width;
                    dgvButtons.SortMode = DataGridViewColumnSortMode.Automatic;
                    dgvButtons.Resizable = Resizable;
                    dgvButtons.DefaultCellStyle.Alignment = cellAlignment;
                    dgvButtons.HeaderCell.Style.Alignment = headerAlignment;
                    if (CellTemplateBackColor.Name.ToString() != "Transparent")
                    {
                        dgvButtons.CellTemplate.Style.BackColor = CellTemplateBackColor;
                    }
                    dgvButtons.DefaultCellStyle.ForeColor = CellTemplateforeColor;
                    ShanuDGV.Columns.Add(dgvButtons);
                    break;
            }    
        }

        #endregion

        //Numeric Textbox event and check for key press event for accepting only numbers for the selected column
        #region Numeric Textbox Events 
        public  void NumeriTextboxEvents(DataGridView ShanuDGV,List<int> columnIndexs)
        {        

            shanuDGVs = ShanuDGV;
            listcolumnIndex=columnIndexs;

            ShanuDGV.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dShanuDGV_EditingControlShowing);
        }
        // grid Editing Control Showing
        private void dShanuDGV_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            e.Control.KeyPress -= new KeyPressEventHandler(itemID_KeyPress);//This line of code resolved my issue
            if (listcolumnIndex.Contains(shanuDGVs.CurrentCell.ColumnIndex))
            {
                TextBox itemID = e.Control as TextBox;
                if (itemID != null)
                {
                    itemID.KeyPress += new KeyPressEventHandler(itemID_KeyPress);
                }
            }
        }
        //Grid Kyey press event
        private void itemID_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar)
                && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }
        #endregion

        // Add an datTime Picker control to existing Textbox Column
        #region DateTimePicker control to textbox column
        public void DateTimePickerEvents(DataGridView ShanuDGV, int columnIndexs,ShanuEventTypes eventtype)
        {
            shanuDGVs = ShanuDGV;
            DateColumnIndex = columnIndexs;
            ShanuDGV.CellClick += new DataGridViewCellEventHandler(shanuDGVs_CellClick);
            //switch (eventtype)
            //{
            //    case ShanuEventTypes.CellClick:
            //        ShanuDGV.CellClick +=new DataGridViewCellEventHandler(shanuDGVs_CellClick);
            //        break;
            //    case ShanuEventTypes.cellContentClick:
            //          ShanuDGV.CellContentClick +=new DataGridViewCellEventHandler(shanuDGVs_CellContentClick);
            //        break;
            //}

            }

        // In this cell click event,DateTime Picker Control will be added to the selected column
        private void shanuDGVs_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == DateColumnIndex)
            {
                shanuDateTimePicker = new DateTimePicker();
                shanuDGVs.Controls.Add(shanuDateTimePicker);
                shanuDateTimePicker.Format = DateTimePickerFormat.Short;
                Rectangle dgvRectangle = shanuDGVs.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true);
                shanuDateTimePicker.Size = new Size(dgvRectangle.Width, dgvRectangle.Height);
                shanuDateTimePicker.Location = new Point(dgvRectangle.X, dgvRectangle.Y);
               // shanuDateTimePicker.Visible = true;
            }
        }


        #endregion
        // Button Click evnet
        #region Button Click Event
        public void DGVClickEvents(DataGridView ShanuDGV, int columnIndexs, ShanuEventTypes eventtype)
        {


            shanuDGVs = ShanuDGV;
           ClickColumnIndex = columnIndexs;
           ShanuDGV.CellContentClick += new DataGridViewCellEventHandler(shanuDGVs_CellContentClick_Event);

        }
        private void shanuDGVs_CellContentClick_Event(object sender, DataGridViewCellEventArgs e)
        {

            if (e.ColumnIndex == ClickColumnIndex)
            {
                MessageBox.Show("Button Clicked " + shanuDGVs.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
            }
        }
        #endregion
        // Button Click Event to show Color Dialog
        #region Button Click Event to show Color Dialog
        public void colorDialogEvents(DataGridView ShanuDGV, int columnIndexs, ShanuEventTypes eventtype)
        {

            shanuDGVs = ShanuDGV;
            ColorColumnIndex = columnIndexs;
          
                    ShanuDGV.CellContentClick += new DataGridViewCellEventHandler(shanuDGVs_CellContentClick);
                  
        }      
            
          private void shanuDGVs_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            
                if (e.ColumnIndex == ColorColumnIndex)
                {
                    MessageBox.Show("Button Clicked " + shanuDGVs.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());

                    ColorDialog cd = new ColorDialog();
                    cd.ShowDialog();
                    shanuDGVs.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = cd.Color;

                }
        }

        #endregion

    }
</int></int>

Now let’s see how to use this Helper Class in our winform project.<o:p>

1) Add the helperClass file in to your project.<o:p>

2) In your form Load call a Method to create your Datagridview Dynamically and call the functions to design, bind and set the each column of your grid.<o:p>

Here we can see I have created a method called "generatedgvColumns” and called this method in my Form Load Event.

  public void generatedgvColumns()
        {

            //First generate the grid Layout Design
            ShanuDGVHelper.Layouts(shanuDGV, Color.LightSteelBlue, Color.AliceBlue, Color.WhiteSmoke, false, Color.SteelBlue, false, false, false);

            //Set Height,width and add panel to your selected control
            ShanuDGVHelper.Generategrid(shanuDGV, pnlShanuGrid, 1000, 600, 10, 10);
          
            // CheckboxColumn creation
            ShanuDGVHelper.Templatecolumn(shanuDGV, ShanuControlTypes.CheckBox, "Chk", "ChkCol", "Check Box Column", true, 60, DataGridViewTriState.True, DataGridViewContentAlignment.MiddleCenter, DataGridViewContentAlignment.MiddleCenter, Color.Transparent, null, "", "", Color.Black);

            // BoundColumn creation
            ShanuDGVHelper.Templatecolumn(shanuDGV, ShanuControlTypes.BoundColumn, "DGVBoundColumn", "DGVBoundColumn", "Bound  Column", true, 120, DataGridViewTriState.True, DataGridViewContentAlignment.MiddleCenter, DataGridViewContentAlignment.MiddleCenter, Color.Transparent, null, "", "", Color.Black);

            // TextboxColumn creation
            ShanuDGVHelper.Templatecolumn(shanuDGV, ShanuControlTypes.TextBox, "DGVTXTColumn", "DGVTXTColumn", "textBox  Column", true, 130, DataGridViewTriState.True, DataGridViewContentAlignment.MiddleLeft, DataGridViewContentAlignment.MiddleLeft, Color.White, null, "", "", Color.Black);

            // NumerictextColumn creation
            ShanuDGVHelper.Templatecolumn(shanuDGV, ShanuControlTypes.TextBox, "DGVNumericTXTColumn", "NCol", "textBox  Column", true, 60, DataGridViewTriState.True, DataGridViewContentAlignment.MiddleRight, DataGridViewContentAlignment.MiddleCenter, Color.MistyRose, null, "", "", Color.Black);

            // BoundColumn creation which will be used as Datetime picker
            ShanuDGVHelper.Templatecolumn(shanuDGV, ShanuControlTypes.BoundColumn, "DGVDateTimepicker", "DGVDateTimepicker", "For Datetime  Column", true, 160, DataGridViewTriState.True, DataGridViewContentAlignment.MiddleLeft, DataGridViewContentAlignment.MiddleLeft, Color.Transparent, null, "", "", Color.Black);

            // ComboBox Column creation
            ShanuDGVHelper.Templatecolumn(shanuDGV, ShanuControlTypes.ComboBox, "DGVComboColumn", "ComboCol", "Combo  Column", true, 160, DataGridViewTriState.True, DataGridViewContentAlignment.MiddleCenter, DataGridViewContentAlignment.MiddleRight, Color.Transparent, dtName, "Name", "Value", Color.Black);


            // Button Column creation
            ShanuDGVHelper.Templatecolumn(shanuDGV, ShanuControlTypes.Button, "DGVButtonColumn", "ButtonCol", "Button  Column", true, 120, DataGridViewTriState.True, DataGridViewContentAlignment.MiddleCenter, DataGridViewContentAlignment.MiddleRight, Color.Transparent, null, "", "", Color.Black);

            // Color Dialog Column creation
            ShanuDGVHelper.Templatecolumn(shanuDGV, ShanuControlTypes.Button, "DGVColorDialogColumn", "ButtonCol", "Button  Column", true, 120, DataGridViewTriState.True, DataGridViewContentAlignment.MiddleCenter, DataGridViewContentAlignment.MiddleRight, Color.Transparent, null, "", "", Color.Black);

            // Numeric Textbox Setting and add the Numeric Textbox column index to list
            lstNumericTextBoxColumns = new List<int>();
            lstNumericTextBoxColumns.Add(shanuDGV.Columns["DGVNumericTXTColumn"].Index);          
         
            //Numeric textbox events to allow only numeric is that column
            objshanudgvHelper.NumeriTextboxEvents(shanuDGV, lstNumericTextBoxColumns);

           
            // Datetime Picker Bind to an existing textbox Column
            objshanudgvHelper.DateTimePickerEvents(shanuDGV, shanuDGV.Columns["DGVDateTimepicker"].Index, ShanuEventTypes.CellClick);

            // Add Color Dialog to Button Column
            objshanudgvHelper.colorDialogEvents(shanuDGV, shanuDGV.Columns["DGVColorDialogColumn"].Index, ShanuEventTypes.cellContentClick);

            // DGV button Click Event
            objshanudgvHelper.DGVClickEvents(shanuDGV, shanuDGV.Columns["DGVButtonColumn"].Index, ShanuEventTypes.cellContentClick);
       

            // Bind data to DGV.
            shanuDGV.DataSource = objDGVBind;



        }
</int>

" ShanuDGVHelper.Layouts()" this  method is used to set the layout of grid like autogenrated or not, BackgroundColor,  AlternatebackColor, RowHeadersVisible and etc.

"ShanuDGVHelper.Generategrid()" this method is used to set the Height, Width and add the datagridview to our selected control, for example here i have added the DGV to a panel control.

" ShanuDGVHelper.Templatecolumn" this method is used to define our Column type as Checkbox ,Textbox, Combobox and etc. To this method we pass the Column Name,Column Header Text,Column Width,Column Back Color and etc.

Points of Interest

Hope this Datagridview Helper Class will be useful for the readers.

History

Version 1.0 - > 2014-11-13.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

syed shanu
Team Leader
India India
Microsoft MVP | Code Project MVP | CSharp Corner MVP | Author | Blogger and always happy to Share what he knows to others. MyBlog

My Interview on Microsoft TechNet Wiki Ninja Link

You may also be interested in...

Comments and Discussions

 
Questionquestion. Pin
Member 1213824624-Nov-15 10:25
memberMember 1213824624-Nov-15 10:25 
Questionvisual studio-12 combo box properties Pin
Member 114000869-Sep-15 17:57
memberMember 114000869-Sep-15 17:57 
Questionnice post!! Pin
deo cabral24-Nov-14 13:30
professionaldeo cabral24-Nov-14 13:30 
AnswerRe: nice post!! Pin
syed shanu24-Nov-14 13:33
professionalsyed shanu24-Nov-14 13:33 
GeneralNice one. Pin
Sandeep Singh Shekhawat19-Nov-14 19:36
professionalSandeep Singh Shekhawat19-Nov-14 19:36 
GeneralRe: Nice one. Pin
syed shanu19-Nov-14 19:39
professionalsyed shanu19-Nov-14 19:39 
GeneralThank you. Pin
Member 1097080818-Nov-14 21:57
memberMember 1097080818-Nov-14 21:57 
GeneralRe: Thank you. Pin
syed shanu19-Nov-14 3:03
professionalsyed shanu19-Nov-14 3:03 
QuestionDifficult setup Pin
Sinisa Hajnal13-Nov-14 22:41
memberSinisa Hajnal13-Nov-14 22:41 
QuestionCannot download your sample project without EXE Pin
fredatcodeproject13-Nov-14 1:37
memberfredatcodeproject13-Nov-14 1:37 
AnswerRe: Cannot download your sample project without EXE Pin
Asma Shanu13-Nov-14 1:48
memberAsma Shanu13-Nov-14 1:48 
GeneralRe: Cannot download your sample project without EXE Pin
fredatcodeproject13-Nov-14 2:18
memberfredatcodeproject13-Nov-14 2:18 
GeneralRe: Cannot download your sample project without EXE Pin
syed shanu13-Nov-14 2:27
professionalsyed shanu13-Nov-14 2:27 
GeneralRe: Cannot download your sample project without EXE Pin
fredatcodeproject13-Nov-14 5:04
memberfredatcodeproject13-Nov-14 5:04 
QuestionVery nice demo Pin
Tridip Bhattacharjee12-Nov-14 20:49
memberTridip Bhattacharjee12-Nov-14 20:49 
AnswerRe: Very nice demo Pin
syed shanu12-Nov-14 20:53
professionalsyed shanu12-Nov-14 20:53 
AnswerRe: Very nice demo Pin
aarif moh shaikh7-Apr-15 18:59
professionalaarif moh shaikh7-Apr-15 18:59 

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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web06-2016 | 2.8.180810.1 | Last Updated 23 Jan 2015
Article Copyright 2015 by syed shanu
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid