Creating Dynamic DataGridView Using Helper Class

Introduction



Why we need a helper class

  • A helper class will make our code part Simple and Standard.
  • All the events of a DataGridView can be defined in the Helper Class. In our form we can call the method from the helper class and make our code simple.
  • A one-time design in the class can be used for the entire project.
  • This will be useful if we change the design only in the class file and there is no need to redesign in each form.

What we have in a 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
  • Image Column
  • DataGridView Events like CellClick,CellContentClick and so on

Here is a sample with Color Dialog from the 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 Windows Forms. In my helper class I have the fallowing function to make the design and bind simple.

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

We can see a few important functions of the class and then I will paste my full class code here.

Layout: This method will set the BackgroundColor, BackColor, AllowUserToAddRows and so on for the DataGridView. In this method we pass our DataGridView and setting all the design part for grid.

  1. #region Layout  
  2.   
  3. public static void Layouts(DataGridView ShanuDGV, Color BackgroundColor, Color RowsBackColor, Color AlternatebackColor, Boolean AutoGenerateColumns, Color HeaderColor, Boolean HeaderVisual, Boolean RowHeadersVisible, Boolean AllowUserToAddRows, Color HeaderForeColor, int headerHeight) {  
  4.     //Grid Back ground Color  
  5.     ShanuDGV.BackgroundColor = BackgroundColor;  
  6.   
  7.     //Grid Back Color  
  8.     ShanuDGV.RowsDefaultCellStyle.BackColor = RowsBackColor;  
  9.   
  10.     //GridColumnStylesCollection Alternate Rows Backcolr  
  11.     ShanuDGV.AlternatingRowsDefaultCellStyle.BackColor = AlternatebackColor;  
  12.   
  13.     // Auto generated here set to tru or false.  
  14.     ShanuDGV.AutoGenerateColumns = AutoGenerateColumns;  
  15.     // ShanuDGV.DefaultCellStyle.Font = new Font("Verdana", 10.25f, FontStyle.Regular);  
  16.     // ShanuDGV.ColumnHeadersDefaultCellStyle.Font = new Font("Calibri", 11, FontStyle.Regular);  
  17.   
  18.     //Column Header back Color  
  19.     ShanuDGV.ColumnHeadersDefaultCellStyle.BackColor = HeaderColor;  
  20.     ShanuDGV.ColumnHeadersDefaultCellStyle.ForeColor = HeaderForeColor;  
  21.     ShanuDGV.ColumnHeadersHeight = headerHeight;  
  22.     //header Visisble  
  23.     ShanuDGV.EnableHeadersVisualStyles = HeaderVisual;  
  24.   
  25.     // Enable the row header  
  26.     ShanuDGV.RowHeadersVisible = RowHeadersVisible;  
  27.   
  28.     // to Hide the Last Empty row here we use false.  
  29.     ShanuDGV.AllowUserToAddRows = AllowUserToAddRows;  
  30. }  
  31. #endregion 

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

  1. #region Generategrid  
  2. public static void Generategrid(DataGridView ShanuDGV, Control cntrlName, int width, int height, int xval, int yval)
  3. {  
  4.     ShanuDGV.Location = new Point(xval, yval);  
  5.     ShanuDGV.Size = new Size(width, height);  
  6.     //ShanuDGV.Dock = docktyope.  
  7.     cntrlName.Controls.Add(ShanuDGV);  
  8. }  
  9. #endregion 

TemplateColumn: This is the important method in the helperclass. Here we pass the DataGridView and define the columns as Bound, Checkbox, TextBox, DateTimePicker and so on. Here we set each column width, Alignment, visibility, BackColor, Font Color and so on.

  1. 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) {  
  2.     switch (ShanuControlTypes) {  
  3.         case ShanuControlTypes.CheckBox:  
  4.             DataGridViewCheckBoxColumn dgvChk = new DataGridViewCheckBoxColumn();  
  5.             dgvChk.ValueType = typeof(bool);  
  6.             dgvChk.Name = cntrlnames;  
  7.   
  8.             dgvChk.HeaderText = Headertext;  
  9.             dgvChk.ToolTipText = ToolTipText;  
  10.             dgvChk.Visible = Visible;  
  11.             dgvChk.Width = width;  
  12.             dgvChk.SortMode = DataGridViewColumnSortMode.Automatic;  
  13.             dgvChk.Resizable = Resizable;  
  14.             dgvChk.DefaultCellStyle.Alignment = cellAlignment;  
  15.             dgvChk.HeaderCell.Style.Alignment = headerAlignment;  
  16.             if (CellTemplateBackColor.Name.ToString() != "Transparent") {  
  17.                 dgvChk.CellTemplate.Style.BackColor = CellTemplateBackColor;  
  18.             }  
  19.             dgvChk.DefaultCellStyle.ForeColor = CellTemplateforeColor;  
  20.             ShanuDGV.Columns.Add(dgvChk);  
  21.             break;  
  22.         case ShanuControlTypes.BoundColumn:  
  23.             DataGridViewColumn col = new DataGridViewTextBoxColumn();  
  24.             col.DataPropertyName = cntrlnames;  
  25.             col.Name = cntrlnames;  
  26.             col.HeaderText = Headertext;  
  27.             col.ToolTipText = ToolTipText;  
  28.             col.Visible = Visible;  
  29.             col.Width = width;  
  30.             col.SortMode = DataGridViewColumnSortMode.Automatic;  
  31.             col.Resizable = Resizable;  
  32.             col.DefaultCellStyle.Alignment = cellAlignment;  
  33.             col.HeaderCell.Style.Alignment = headerAlignment;  
  34.             if (CellTemplateBackColor.Name.ToString() != "Transparent") {  
  35.                 col.CellTemplate.Style.BackColor = CellTemplateBackColor;  
  36.             }  
  37.             col.DefaultCellStyle.ForeColor = CellTemplateforeColor;  
  38.             ShanuDGV.Columns.Add(col);  
  39.             break;  
  40.         case ShanuControlTypes.TextBox:  
  41.             DataGridViewTextBoxColumn dgvText = new DataGridViewTextBoxColumn();  
  42.             dgvText.ValueType = typeof(decimal);  
  43.             dgvText.DataPropertyName = cntrlnames;  
  44.   
  45.             dgvText.Name = cntrlnames;  
  46.             dgvText.HeaderText = Headertext;  
  47.             dgvText.ToolTipText = ToolTipText;  
  48.             dgvText.Visible = Visible;  
  49.             dgvText.Width = width;  
  50.             dgvText.SortMode = DataGridViewColumnSortMode.Automatic;  
  51.             dgvText.Resizable = Resizable;  
  52.             dgvText.DefaultCellStyle.Alignment = cellAlignment;  
  53.             dgvText.HeaderCell.Style.Alignment = headerAlignment;  
  54.             if (CellTemplateBackColor.Name.ToString() != "Transparent") {  
  55.                 dgvText.CellTemplate.Style.BackColor = CellTemplateBackColor;  
  56.             }  
  57.             dgvText.DefaultCellStyle.ForeColor = CellTemplateforeColor;  
  58.             ShanuDGV.Columns.Add(dgvText);  
  59.             break;  
  60.         case ShanuControlTypes.ComboBox:  
  61.             DataGridViewComboBoxColumn dgvcombo = new DataGridViewComboBoxColumn();  
  62.             dgvcombo.ValueType = typeof(decimal);  
  63.             dgvcombo.Name = cntrlnames;  
  64.             dgvcombo.DataSource = dtsource;  
  65.             dgvcombo.DisplayMember = DisplayMember;  
  66.             dgvcombo.ValueMember = ValueMember;  
  67.             dgvcombo.HeaderText = Headertext;  
  68.             dgvcombo.ToolTipText = ToolTipText;  
  69.             dgvcombo.Visible = Visible;  
  70.             dgvcombo.Width = width;  
  71.             dgvcombo.SortMode = DataGridViewColumnSortMode.Automatic;  
  72.             dgvcombo.Resizable = Resizable;  
  73.             dgvcombo.DefaultCellStyle.Alignment = cellAlignment;  
  74.             dgvcombo.HeaderCell.Style.Alignment = headerAlignment;  
  75.             if (CellTemplateBackColor.Name.ToString() != "Transparent") {  
  76.                 dgvcombo.CellTemplate.Style.BackColor = CellTemplateBackColor;  
  77.   
  78.             }  
  79.             dgvcombo.DefaultCellStyle.ForeColor = CellTemplateforeColor;  
  80.             ShanuDGV.Columns.Add(dgvcombo);  
  81.             break;  
  82.   
  83.         case ShanuControlTypes.Button:  
  84.             DataGridViewButtonColumn dgvButtons = new DataGridViewButtonColumn();  
  85.             dgvButtons.Name = cntrlnames;  
  86.             dgvButtons.FlatStyle = FlatStyle.Popup;  
  87.             dgvButtons.DataPropertyName = cntrlnames;  
  88.             dgvButtons.HeaderText = Headertext;  
  89.             dgvButtons.ToolTipText = ToolTipText;  
  90.             dgvButtons.Visible = Visible;  
  91.             dgvButtons.Width = width;  
  92.             dgvButtons.SortMode = DataGridViewColumnSortMode.Automatic;  
  93.             dgvButtons.Resizable = Resizable;  
  94.             dgvButtons.DefaultCellStyle.Alignment = cellAlignment;  
  95.             dgvButtons.HeaderCell.Style.Alignment = headerAlignment;  
  96.             if (CellTemplateBackColor.Name.ToString() != "Transparent") {  
  97.                 dgvButtons.CellTemplate.Style.BackColor = CellTemplateBackColor;  
  98.             }  
  99.             dgvButtons.DefaultCellStyle.ForeColor = CellTemplateforeColor;  
  100.             ShanuDGV.Columns.Add(dgvButtons);  
  101.             break;  
  102.         case ShanuControlTypes.ImageColumn:  
  103.             DataGridViewImageColumn dgvnestedBtn = new DataGridViewImageColumn();  
  104.             dgvnestedBtn.Name = cntrlnames;  
  105.             dgvnestedBtn.Image = Image.FromFile("shanu.JPG"); //global::ShanuDGVHelper_Demo.Properties.Resources.toggle;  
  106.             dgvnestedBtn.HeaderText = Headertext;  
  107.             dgvnestedBtn.ToolTipText = ToolTipText;  
  108.             // dgvnestedBtn.DataPropertyName = cntrlnames;  
  109.             dgvnestedBtn.Visible = Visible;  
  110.             dgvnestedBtn.Width = width;  
  111.             dgvnestedBtn.SortMode = DataGridViewColumnSortMode.Automatic;  
  112.             dgvnestedBtn.Resizable = Resizable;  
  113.             dgvnestedBtn.DefaultCellStyle.Alignment = cellAlignment;  
  114.             dgvnestedBtn.HeaderCell.Style.Alignment = headerAlignment;  
  115.             ShanuDGV.Columns.Add(dgvnestedBtn);  
  116.             break;  
  117.     }  

NumerictextBoxEvent: In this method we pass the DataGridView and list of ColumnIndexes that need to be set as a NumbericTextbox Column. Using the EditingControlShowing Event of DataGridView, I check for all the columns that need to be accepted as only numbers from the TextBox.

  1. //Numeric Textbox event and check for key press event for accepting only numbers for the selected column  
  2. #region Numeric Textbox Events  
  3. public void NumeriTextboxEvents(DataGridView ShanuDGV, List < int > columnIndexs) {  
  4.   
  5.     shanuDGVs = ShanuDGV;  
  6.     listcolumnIndex = columnIndexs;  
  7.   
  8.     ShanuDGV.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dShanuDGV_EditingControlShowing);  
  9. }  
  10. // grid Editing Control Showing  
  11. private void dShanuDGV_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) {  
  12.     e.Control.KeyPress -= new KeyPressEventHandler(itemID_KeyPress); //This line of code resolved my issue  
  13.     if (listcolumnIndex.Contains(shanuDGVs.CurrentCell.ColumnIndex)) {  
  14.         TextBox itemID = e.Control as TextBox;  
  15.         if (itemID != null) {  
  16.             itemID.KeyPress += new KeyPressEventHandler(itemID_KeyPress);  
  17.         }  
  18.     }  
  19. }  
  20. //Grid Kyey press event  
  21. private void itemID_KeyPress(object sender, KeyPressEventArgs e) {  
  22.     if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar)) {  
  23.         e.Handled = true;  
  24.     }  
  25. }  
  26. #endregion 

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

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Windows.Forms;  
  9. using System.Data;  
  10.   
  11. /// <summary>  
  12. /// Author : Shanu  
  13. /// Create date : 2014-11-11  
  14. /// Description : ShanuDGVHelper  
  15. /// Latest  
  16. /// Modifier : Shanu  
  17. /// Modify date : 2014-11-11  
  18. /// </summary>  
  19. namespace ShanuDGVHelper_Demo
  20. {  
  21.     class ShanuDGVHelper {#region Variables  
  22.         public DataGridView shanuDGVs = new DataGridView();  
  23.         List < int > listcolumnIndex;  
  24.         int DateColumnIndex = 0;  
  25.         int ColorColumnIndex = 0;  
  26.         int ClickColumnIndex = 0;  
  27.         DateTimePicker shanuDateTimePicker;  
  28.         String EventFucntions;  
  29.         int imgColumnIndex = 0;  
  30.         DataTable objDGVBind = new DataTable();  
  31.         Boolean imgBindchk = false;  
  32.         #endregion   
  33.         //Set all the telerik Grid layout  
  34.         #region Layout  
  35.         public static void Layouts(DataGridView ShanuDGV, Color BackgroundColor, Color RowsBackColor, Color AlternatebackColor, Boolean AutoGenerateColumns, Color HeaderColor, Boolean HeaderVisual, Boolean RowHeadersVisible, Boolean AllowUserToAddRows, Color HeaderForeColor, int headerHeight) {  
  36.             //Grid Back ground Color  
  37.             ShanuDGV.BackgroundColor = BackgroundColor;  
  38.             //Grid Back Color  
  39.             ShanuDGV.RowsDefaultCellStyle.BackColor = RowsBackColor;  
  40.             //GridColumnStylesCollection Alternate Rows Backcolr  
  41.             ShanuDGV.AlternatingRowsDefaultCellStyle.BackColor = AlternatebackColor;  
  42.             // Auto generated here set to tru or false.  
  43.             ShanuDGV.AutoGenerateColumns = AutoGenerateColumns;  
  44.             // ShanuDGV.DefaultCellStyle.Font = new Font("Verdana", 10.25f, FontStyle.Regular);  
  45.             // ShanuDGV.ColumnHeadersDefaultCellStyle.Font = new Font("Calibri", 11, FontStyle.Regular);  
  46.             //Column Header back Color  
  47.             ShanuDGV.ColumnHeadersDefaultCellStyle.BackColor = HeaderColor;  
  48.             ShanuDGV.ColumnHeadersDefaultCellStyle.ForeColor = HeaderForeColor;  
  49.             ShanuDGV.ColumnHeadersHeight = headerHeight;  
  50.             //header Visisble  
  51.             ShanuDGV.EnableHeadersVisualStyles = HeaderVisual;  
  52.             // Enable the row header  
  53.             ShanuDGV.RowHeadersVisible = RowHeadersVisible;  
  54.             // to Hide the Last Empty row here we use false.  
  55.             ShanuDGV.AllowUserToAddRows = AllowUserToAddRows;  
  56.         }
  57.         #endregion  
  58.         //Add your grid to your selected Control and set height,width,position of your grid.  
  59.         #region Generategrid  
  60.         public static void Generategrid(DataGridView ShanuDGV, Control cntrlName, int width, int height, int xval, int yval) {  
  61.             ShanuDGV.Location = new Point(xval, yval);  
  62.             ShanuDGV.Size = new Size(width, height);  
  63.             //ShanuDGV.Dock = docktyope.  
  64.             cntrlName.Controls.Add(ShanuDGV);  
  65.         }
  66.          #endregion
  67.         //Template Column In this column we can add Textbox,Lable,Check Box,Dropdown box and etc  
  68.         #region Templatecolumn  
  69.         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) {  
  70.             switch (ShanuControlTypes) {  
  71.                 case ShanuControlTypes.CheckBox:  
  72.                     DataGridViewCheckBoxColumn dgvChk = new DataGridViewCheckBoxColumn();  
  73.                     dgvChk.ValueType = typeof(bool);  
  74.                     dgvChk.Name = cntrlnames;  
  75.                     dgvChk.HeaderText = Headertext;  
  76.                     dgvChk.ToolTipText = ToolTipText;  
  77.                     dgvChk.Visible = Visible;  
  78.                     dgvChk.Width = width;  
  79.                     dgvChk.SortMode = DataGridViewColumnSortMode.Automatic;  
  80.                     dgvChk.Resizable = Resizable;  
  81.                     dgvChk.DefaultCellStyle.Alignment = cellAlignment;  
  82.                     dgvChk.HeaderCell.Style.Alignment = headerAlignment;  
  83.                     if (CellTemplateBackColor.Name.ToString() != "Transparent") {  
  84.                         dgvChk.CellTemplate.Style.BackColor = CellTemplateBackColor;  
  85.                     }  
  86.                     dgvChk.DefaultCellStyle.ForeColor = CellTemplateforeColor;  
  87.                     ShanuDGV.Columns.Add(dgvChk);  
  88.                     break;  
  89.                 case ShanuControlTypes.BoundColumn:  
  90.                     DataGridViewColumn col = new DataGridViewTextBoxColumn();  
  91.                     col.DataPropertyName = cntrlnames;  
  92.                     col.Name = cntrlnames;  
  93.                     col.HeaderText = Headertext;  
  94.                     col.ToolTipText = ToolTipText;  
  95.                     col.Visible = Visible;  
  96.                     col.Width = width;  
  97.                     col.SortMode = DataGridViewColumnSortMode.Automatic;  
  98.                     col.Resizable = Resizable;  
  99.                     col.DefaultCellStyle.Alignment = cellAlignment;  
  100.                     col.HeaderCell.Style.Alignment = headerAlignment;  
  101.                     if (CellTemplateBackColor.Name.ToString() != "Transparent") {  
  102.                         col.CellTemplate.Style.BackColor = CellTemplateBackColor;  
  103.                     }  
  104.                     col.DefaultCellStyle.ForeColor = CellTemplateforeColor;  
  105.                     ShanuDGV.Columns.Add(col);  
  106.                     break;  
  107.                 case ShanuControlTypes.TextBox:  
  108.                     DataGridViewTextBoxColumn dgvText = new DataGridViewTextBoxColumn();  
  109.                     dgvText.ValueType = typeof(decimal);  
  110.                     dgvText.DataPropertyName = cntrlnames;  
  111.                     dgvText.Name = cntrlnames;  
  112.                     dgvText.HeaderText = Headertext;  
  113.                     dgvText.ToolTipText = ToolTipText;  
  114.                     dgvText.Visible = Visible;  
  115.                     dgvText.Width = width;  
  116.                     dgvText.SortMode = DataGridViewColumnSortMode.Automatic;  
  117.                     dgvText.Resizable = Resizable;  
  118.                     dgvText.DefaultCellStyle.Alignment = cellAlignment;  
  119.                     dgvText.HeaderCell.Style.Alignment = headerAlignment;  
  120.                     if (CellTemplateBackColor.Name.ToString() != "Transparent") {  
  121.                         dgvText.CellTemplate.Style.BackColor = CellTemplateBackColor;  
  122.                     }  
  123.                     dgvText.DefaultCellStyle.ForeColor = CellTemplateforeColor;  
  124.                     ShanuDGV.Columns.Add(dgvText);  
  125.                     break;  
  126.                 case ShanuControlTypes.ComboBox:  
  127.                     DataGridViewComboBoxColumn dgvcombo = new DataGridViewComboBoxColumn();  
  128.                     dgvcombo.ValueType = typeof(decimal);  
  129.                     dgvcombo.Name = cntrlnames;  
  130.                     dgvcombo.DataSource = dtsource;  
  131.                     dgvcombo.DisplayMember = DisplayMember;  
  132.                     dgvcombo.ValueMember = ValueMember;  
  133.                     dgvcombo.HeaderText = Headertext;  
  134.                     dgvcombo.ToolTipText = ToolTipText;  
  135.                     dgvcombo.Visible = Visible;  
  136.                     dgvcombo.Width = width;  
  137.                     dgvcombo.SortMode = DataGridViewColumnSortMode.Automatic;  
  138.                     dgvcombo.Resizable = Resizable;  
  139.                     dgvcombo.DefaultCellStyle.Alignment = cellAlignment;  
  140.                     dgvcombo.HeaderCell.Style.Alignment = headerAlignment;  
  141.                     if (CellTemplateBackColor.Name.ToString() != "Transparent") {  
  142.                         dgvcombo.CellTemplate.Style.BackColor = CellTemplateBackColor;  
  143.   
  144.                     }  
  145.                     dgvcombo.DefaultCellStyle.ForeColor = CellTemplateforeColor;  
  146.                     ShanuDGV.Columns.Add(dgvcombo);  
  147.                     break;
  148.                 case ShanuControlTypes.Button:  
  149.                     DataGridViewButtonColumn dgvButtons = new DataGridViewButtonColumn();  
  150.                     dgvButtons.Name = cntrlnames;  
  151.                     dgvButtons.FlatStyle = FlatStyle.Popup;  
  152.                     dgvButtons.DataPropertyName = cntrlnames;  
  153.                     dgvButtons.HeaderText = Headertext;  
  154.                     dgvButtons.ToolTipText = ToolTipText;  
  155.                     dgvButtons.Visible = Visible;  
  156.                     dgvButtons.Width = width;  
  157.                     dgvButtons.SortMode = DataGridViewColumnSortMode.Automatic;  
  158.                     dgvButtons.Resizable = Resizable;  
  159.                     dgvButtons.DefaultCellStyle.Alignment = cellAlignment;  
  160.                     dgvButtons.HeaderCell.Style.Alignment = headerAlignment;  
  161.                     if (CellTemplateBackColor.Name.ToString() != "Transparent") {  
  162.                         dgvButtons.CellTemplate.Style.BackColor = CellTemplateBackColor;  
  163.                     }  
  164.                     dgvButtons.DefaultCellStyle.ForeColor = CellTemplateforeColor;  
  165.                     ShanuDGV.Columns.Add(dgvButtons);  
  166.                     break;  
  167.                 case ShanuControlTypes.ImageColumn:  
  168.                     DataGridViewImageColumn dgvnestedBtn = new DataGridViewImageColumn();  
  169.                     dgvnestedBtn.Name = cntrlnames;  
  170.                     dgvnestedBtn.Image = Image.FromFile("shanu.JPG"); //global::ShanuDGVHelper_Demo.Properties.Resources.toggle;  
  171.                     dgvnestedBtn.HeaderText = Headertext;  
  172.                     dgvnestedBtn.ToolTipText = ToolTipText;  
  173.                     // dgvnestedBtn.DataPropertyName = cntrlnames;  
  174.                     dgvnestedBtn.Visible = Visible;  
  175.                     dgvnestedBtn.Width = width;  
  176.                     dgvnestedBtn.SortMode = DataGridViewColumnSortMode.Automatic;  
  177.                     dgvnestedBtn.Resizable = Resizable;  
  178.                     dgvnestedBtn.DefaultCellStyle.Alignment = cellAlignment;  
  179.                     dgvnestedBtn.HeaderCell.Style.Alignment = headerAlignment;  
  180.                     ShanuDGV.Columns.Add(dgvnestedBtn);  
  181.                     break;  
  182.             }  
  183.         }
  184.         #endregion  

  185.         #region Image Column bind using Cellformatting  
  186.         public void datagridImageAddEvent(DataGridView ShanuDGV, int imgColIndex, DataTable objDGVBinds) {  
  187.             shanuDGVs = ShanuDGV;  
  188.             objDGVBind = objDGVBinds;  
  189.             imgColumnIndex = imgColIndex;  
  190.             shanuDGVs.CellFormatting += new DataGridViewCellFormattingEventHandler(shanuDGVs_CellFormatting);  
  191.         }  
  192.         private void shanuDGVs_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) {  
  193.             if (e.ColumnIndex == imgColumnIndex) {  
  194.                 if (imgBindchk == false) {  
  195.                     shanuDGVs.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = Image.FromFile(objDGVBind.Rows[e.RowIndex][imgColumnIndex].ToString());  
  196.                     if (e.RowIndex == objDGVBind.Rows.Count - 1) {  
  197.                         imgBindchk = true;  
  198.                     }  
  199.                 }  
  200.             }  
  201.         }
  202.         #endregion  
  203.         //Numeric Textbox event and check for key press event for accepting only numbers for the selected column  
  204.         #region Numeric Textbox Events  
  205.         public void NumeriTextboxEvents(DataGridView ShanuDGV, List < int > columnIndexs) {  
  206.             shanuDGVs = ShanuDGV;  
  207.             listcolumnIndex = columnIndexs;  
  208.             ShanuDGV.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dShanuDGV_EditingControlShowing);  
  209.         }  
  210.         // grid Editing Control Showing  
  211.         private void dShanuDGV_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) {  
  212.             e.Control.KeyPress -= new KeyPressEventHandler(itemID_KeyPress); //This line of code resolved my issue  
  213.             if (listcolumnIndex.Contains(shanuDGVs.CurrentCell.ColumnIndex)) {  
  214.                 TextBox itemID = e.Control as TextBox;  
  215.                 if (itemID != null) {  
  216.                     itemID.KeyPress += new KeyPressEventHandler(itemID_KeyPress);  
  217.                 }  
  218.             }  
  219.         }  
  220.         //Grid Kyey press event  
  221.         private void itemID_KeyPress(object sender, KeyPressEventArgs e) {  
  222.             if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar)) {  
  223.                 e.Handled = true;  
  224.             }  
  225.         }#endregion  
  226.         // Add an datTime Picker control to existing Textbox Column  
  227.         #region DateTimePicker control to textbox column  
  228.         public void DateTimePickerEvents(DataGridView ShanuDGV, int columnIndexs, ShanuEventTypes eventtype) {  
  229.             shanuDGVs = ShanuDGV;  
  230.             DateColumnIndex = columnIndexs;  
  231.             ShanuDGV.CellClick += new DataGridViewCellEventHandler(shanuDGVs_CellClick);  
  232.             //switch (eventtype)  
  233.             //{  
  234.             // case ShanuEventTypes.CellClick:  
  235.             // ShanuDGV.CellClick +=new DataGridViewCellEventHandler(shanuDGVs_CellClick);  
  236.             // break;  
  237.             // case ShanuEventTypes.cellContentClick:  
  238.             // ShanuDGV.CellContentClick +=new DataGridViewCellEventHandler(shanuDGVs_CellContentClick);  
  239.             // break;  
  240.             //}  
  241.         }
  242.         // In this cell click event,DateTime Picker Control will be added to the selected column  
  243.         private void shanuDGVs_CellClick(object sender, DataGridViewCellEventArgs e) {  
  244.             if (e.ColumnIndex == DateColumnIndex) {  
  245.                 shanuDateTimePicker = new DateTimePicker();  
  246.                 shanuDGVs.Controls.Add(shanuDateTimePicker);  
  247.                 shanuDateTimePicker.Format = DateTimePickerFormat.Short;  
  248.                 Rectangle dgvRectangle = shanuDGVs.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true);  
  249.                 shanuDateTimePicker.Size = new Size(dgvRectangle.Width, dgvRectangle.Height);  
  250.                 shanuDateTimePicker.Location = new Point(dgvRectangle.X, dgvRectangle.Y);  
  251.                 // shanuDateTimePicker.Visible = true;  
  252.             }  
  253.         }  
  254.         #endregion  
  255.         // Button Click evnet  
  256.         #region Button Click Event  
  257.         public void DGVClickEvents(DataGridView ShanuDGV, int columnIndexs, ShanuEventTypes eventtype)
  258.         {  
  259.             shanuDGVs = ShanuDGV;  
  260.             ClickColumnIndex = columnIndexs;  
  261.             ShanuDGV.CellContentClick += new DataGridViewCellEventHandler(shanuDGVs_CellContentClick_Event);  
  262.         }  
  263.         private void shanuDGVs_CellContentClick_Event(object sender, DataGridViewCellEventArgs e) {  
  264.             if (e.ColumnIndex == ClickColumnIndex)
  265.             {  
  266.                 MessageBox.Show("Button Clicked " + shanuDGVs.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());  
  267.             }  
  268.         }
  269.          #endregion  
  270.         // Button Click Event to show Color Dialog  
  271.         #region Button Click Event to show Color Dialog  
  272.         public void colorDialogEvents(DataGridView ShanuDGV, int columnIndexs, ShanuEventTypes eventtype) {  
  273.             shanuDGVs = ShanuDGV;  
  274.             ColorColumnIndex = columnIndexs;  
  275.             ShanuDGV.CellContentClick += new DataGridViewCellEventHandler(shanuDGVs_CellContentClick);  
  276.         }  
  277.         private void shanuDGVs_CellContentClick(object sender, DataGridViewCellEventArgs e) {  
  278.             if (e.ColumnIndex == ColorColumnIndex) {  
  279.                 MessageBox.Show("Button Clicked " + shanuDGVs.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());  
  280.                 ColorDialog cd = new ColorDialog();  
  281.                 cd.ShowDialog();  
  282.                 shanuDGVs.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = cd.Color;  
  283.             }  
  284.         }  
  285.         #endregion   
  286.     }  
  287. }  
  288. //Enam decalaration for DataGridView Column Type ex like Textbox Column ,Button Column  
  289. public enum ShanuControlTypes {  
  290.     BoundColumn, TextBox, ComboBox, CheckBox, DateTimepicker, Button, NumericTextBox, ColorDialog, ImageColumn  
  291. }  
  292. public enum ShanuEventTypes {  
  293.     CellClick, cellContentClick, EditingControlShowing  

Now let’s see how to use this Helper Class in our Windows Forms project.

  1. Add the helperClass file to your project.
  2. In your form Load call a Method to create your DataGridView dynamically and call the functions to design, bind and set each column of your grid.

Here we can see I have created a method called "generatedgvColumns” and call this method in my Form Load Event.In this method i will set the Hegith,Width and styles to the datagridview,create all columns with Column type as TextboxColumn,ButtonColumn,CheckBoxColumn,ImageColumn,DateTimePickerColumn and etc,Set events for grid like CellContentClick event and etc, bind the Dataseource to the grid.

  1. public void generatedgvColumns()
  2. {  
  3.   
  4.     //First generate the grid Layout Design  
  5.     ShanuDGVHelper.Layouts(shanuDGV, Color.LightSteelBlue, Color.AliceBlue, Color.LightSkyBlue, false, Color.SteelBlue, falsefalsefalse, Color.White, 40);  
  6.   
  7.     //Set Height,width and add panel to your selected control  
  8.     ShanuDGVHelper.Generategrid(shanuDGV, pnlShanuGrid, 1000, 600, 10, 10);  
  9.   
  10.     // CheckboxColumn creation  
  11.     ShanuDGVHelper.Templatecolumn(shanuDGV, ShanuControlTypes.CheckBox, "Chk""CHKCOL""Check Box Column"true, 60, DataGridViewTriState.True, DataGridViewContentAlignment.MiddleCenter, DataGridViewContentAlignment.MiddleCenter, Color.Transparent, null"""", Color.Black);  
  12.   
  13.     // BoundColumn creation  
  14.     ShanuDGVHelper.Templatecolumn(shanuDGV, ShanuControlTypes.BoundColumn, "DGVBoundColumn""BOUNDCOL""Bound Column"true, 120, DataGridViewTriState.True, DataGridViewContentAlignment.MiddleCenter, DataGridViewContentAlignment.MiddleCenter, Color.Transparent, null"""", Color.Black);  
  15.   
  16.     // TextboxColumn creation  
  17.     ShanuDGVHelper.Templatecolumn(shanuDGV, ShanuControlTypes.TextBox, "DGVTXTColumn""TXTCOL""textBox Column"true, 130, DataGridViewTriState.True, DataGridViewContentAlignment.MiddleLeft, DataGridViewContentAlignment.MiddleLeft, Color.White, null"""", Color.Black);  
  18.   
  19.     // NumerictextColumn creation  
  20.     ShanuDGVHelper.Templatecolumn(shanuDGV, ShanuControlTypes.TextBox, "DGVNumericTXTColumn""NO.COL""textBox Column"true, 60, DataGridViewTriState.True, DataGridViewContentAlignment.MiddleRight, DataGridViewContentAlignment.MiddleCenter, Color.MistyRose, null"""", Color.Black);  
  21.   
  22.     // BoundColumn creation which will be used as Datetime picker  
  23.     ShanuDGVHelper.Templatecolumn(shanuDGV, ShanuControlTypes.BoundColumn, "DGVDateTimepicker""DATECOL""For Datetime Column"true, 160, DataGridViewTriState.True, DataGridViewContentAlignment.MiddleLeft, DataGridViewContentAlignment.MiddleLeft, Color.Transparent, null"""", Color.Black);  
  24.   
  25.     // ComboBox Column creation  
  26.     ShanuDGVHelper.Templatecolumn(shanuDGV, ShanuControlTypes.ComboBox, "DGVComboColumn""COMBOCOL""Combo Column"true, 160, DataGridViewTriState.True, DataGridViewContentAlignment.MiddleCenter, DataGridViewContentAlignment.MiddleRight, Color.Transparent, dtName, "Name""Value", Color.Black);  
  27.   
  28.   
  29.     // Button Column creation  
  30.     ShanuDGVHelper.Templatecolumn(shanuDGV, ShanuControlTypes.Button, "DGVButtonColumn""BUTTONCOL""Button Column"true, 120, DataGridViewTriState.True, DataGridViewContentAlignment.MiddleCenter, DataGridViewContentAlignment.MiddleRight, Color.Transparent, null"""", Color.Black);  
  31.   
  32.     // Color Dialog Column creation  
  33.     ShanuDGVHelper.Templatecolumn(shanuDGV, ShanuControlTypes.Button, "DGVColorDialogColumn""COLORPICKER""Button Column"true, 120, DataGridViewTriState.True, DataGridViewContentAlignment.MiddleCenter, DataGridViewContentAlignment.MiddleRight, Color.Transparent, null"""", Color.Black);  
  34.   
  35.     // Image Column creation  
  36.     ShanuDGVHelper.Templatecolumn(shanuDGV, ShanuControlTypes.ImageColumn, "DGVImgColumn""IMGCOL""IMG Column"true, 80, DataGridViewTriState.True, DataGridViewContentAlignment.MiddleCenter, DataGridViewContentAlignment.MiddleRight, Color.Transparent, null"""", Color.Black);  
  37.   
  38.   
  39.     // Numeric Textbox Setting and add the Numeric Textbox column index to list  
  40.     lstNumericTextBoxColumns = new List < int > ();  
  41.     lstNumericTextBoxColumns.Add(shanuDGV.Columns["DGVNumericTXTColumn"].Index);  
  42.   
  43.     //Numeric textbox events to allow only numeric is that column  
  44.     objshanudgvHelper.NumeriTextboxEvents(shanuDGV, lstNumericTextBoxColumns);  
  45.   
  46.     //Image Column bind image  
  47.     objshanudgvHelper.datagridImageAddEvent(shanuDGV, shanuDGV.Columns["DGVImgColumn"].Index, dtSource);  
  48.   
  49.   
  50.     // Datetime Picker Bind to an existing textbox Column  
  51.     objshanudgvHelper.DateTimePickerEvents(shanuDGV, shanuDGV.Columns["DGVDateTimepicker"].Index, ShanuEventTypes.CellClick);  
  52.   
  53.     // Add Color Dialog to Button Column  
  54.     objshanudgvHelper.colorDialogEvents(shanuDGV, shanuDGV.Columns["DGVColorDialogColumn"].Index, ShanuEventTypes.cellContentClick);  
  55.   
  56.     // DGV button Click Event  
  57.     objshanudgvHelper.DGVClickEvents(shanuDGV, shanuDGV.Columns["DGVButtonColumn"].Index, ShanuEventTypes.cellContentClick);  
  58.   
  59.   
  60.     // Bind data to DGV.  
  61.     shanuDGV.DataSource = dtSource;   
  62. }  
  63. #endregion 


"ShanuDGVHelper.Layouts()" this method sets the layout of the grid, like autogenrated or not, BackgroundColor, AlternatebackColor, RowHeadersVisible and so on.

"ShanuDGVHelper.Generategrid()"
this method sets the Height, Width and adds the DataGridView to our selected control, for example here I have added the DGV to a panel control.

" ShanuDGVHelper.Templatecolumn"
this method defines our Column type as Checkbox,TextBox, Combobox and so on. For this method we pass the Column Name, Column Header Text, Column Width, Column Back Color and so on.


Similar Articles