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. 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) {
  3. //Grid Back ground Color
  4. ShanuDGV.BackgroundColor = BackgroundColor;
  5. //Grid Back Color
  6. ShanuDGV.RowsDefaultCellStyle.BackColor = RowsBackColor;
  7. //GridColumnStylesCollection Alternate Rows Backcolr
  8. ShanuDGV.AlternatingRowsDefaultCellStyle.BackColor = AlternatebackColor;
  9. // Auto generated here set to tru or false.
  10. ShanuDGV.AutoGenerateColumns = AutoGenerateColumns;
  11. // ShanuDGV.DefaultCellStyle.Font = new Font("Verdana", 10.25f, FontStyle.Regular);
  12. // ShanuDGV.ColumnHeadersDefaultCellStyle.Font = new Font("Calibri", 11, FontStyle.Regular);
  13. //Column Header back Color
  14. ShanuDGV.ColumnHeadersDefaultCellStyle.BackColor = HeaderColor;
  15. ShanuDGV.ColumnHeadersDefaultCellStyle.ForeColor = HeaderForeColor;
  16. ShanuDGV.ColumnHeadersHeight = headerHeight;
  17. //header Visisble
  18. ShanuDGV.EnableHeadersVisualStyles = HeaderVisual;
  19. // Enable the row header
  20. ShanuDGV.RowHeadersVisible = RowHeadersVisible;
  21. // to Hide the Last Empty row here we use false.
  22. ShanuDGV.AllowUserToAddRows = AllowUserToAddRows;
  23. }
  24. #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. dgvChk.HeaderText = Headertext;
  8. dgvChk.ToolTipText = ToolTipText;
  9. dgvChk.Visible = Visible;
  10. dgvChk.Width = width;
  11. dgvChk.SortMode = DataGridViewColumnSortMode.Automatic;
  12. dgvChk.Resizable = Resizable;
  13. dgvChk.DefaultCellStyle.Alignment = cellAlignment;
  14. dgvChk.HeaderCell.Style.Alignment = headerAlignment;
  15. if (CellTemplateBackColor.Name.ToString() != "Transparent") {
  16. dgvChk.CellTemplate.Style.BackColor = CellTemplateBackColor;
  17. }
  18. dgvChk.DefaultCellStyle.ForeColor = CellTemplateforeColor;
  19. ShanuDGV.Columns.Add(dgvChk);
  20. break;
  21. case ShanuControlTypes.BoundColumn:
  22. DataGridViewColumn col = new DataGridViewTextBoxColumn();
  23. col.DataPropertyName = cntrlnames;
  24. col.Name = cntrlnames;
  25. col.HeaderText = Headertext;
  26. col.ToolTipText = ToolTipText;
  27. col.Visible = Visible;
  28. col.Width = width;
  29. col.SortMode = DataGridViewColumnSortMode.Automatic;
  30. col.Resizable = Resizable;
  31. col.DefaultCellStyle.Alignment = cellAlignment;
  32. col.HeaderCell.Style.Alignment = headerAlignment;
  33. if (CellTemplateBackColor.Name.ToString() != "Transparent") {
  34. col.CellTemplate.Style.BackColor = CellTemplateBackColor;
  35. }
  36. col.DefaultCellStyle.ForeColor = CellTemplateforeColor;
  37. ShanuDGV.Columns.Add(col);
  38. break;
  39. case ShanuControlTypes.TextBox:
  40. DataGridViewTextBoxColumn dgvText = new DataGridViewTextBoxColumn();
  41. dgvText.ValueType = typeof(decimal);
  42. dgvText.DataPropertyName = cntrlnames;
  43. dgvText.Name = cntrlnames;
  44. dgvText.HeaderText = Headertext;
  45. dgvText.ToolTipText = ToolTipText;
  46. dgvText.Visible = Visible;
  47. dgvText.Width = width;
  48. dgvText.SortMode = DataGridViewColumnSortMode.Automatic;
  49. dgvText.Resizable = Resizable;
  50. dgvText.DefaultCellStyle.Alignment = cellAlignment;
  51. dgvText.HeaderCell.Style.Alignment = headerAlignment;
  52. if (CellTemplateBackColor.Name.ToString() != "Transparent") {
  53. dgvText.CellTemplate.Style.BackColor = CellTemplateBackColor;
  54. }
  55. dgvText.DefaultCellStyle.ForeColor = CellTemplateforeColor;
  56. ShanuDGV.Columns.Add(dgvText);
  57. break;
  58. case ShanuControlTypes.ComboBox:
  59. DataGridViewComboBoxColumn dgvcombo = new DataGridViewComboBoxColumn();
  60. dgvcombo.ValueType = typeof(decimal);
  61. dgvcombo.Name = cntrlnames;
  62. dgvcombo.DataSource = dtsource;
  63. dgvcombo.DisplayMember = DisplayMember;
  64. dgvcombo.ValueMember = ValueMember;
  65. dgvcombo.HeaderText = Headertext;
  66. dgvcombo.ToolTipText = ToolTipText;
  67. dgvcombo.Visible = Visible;
  68. dgvcombo.Width = width;
  69. dgvcombo.SortMode = DataGridViewColumnSortMode.Automatic;
  70. dgvcombo.Resizable = Resizable;
  71. dgvcombo.DefaultCellStyle.Alignment = cellAlignment;
  72. dgvcombo.HeaderCell.Style.Alignment = headerAlignment;
  73. if (CellTemplateBackColor.Name.ToString() != "Transparent") {
  74. dgvcombo.CellTemplate.Style.BackColor = CellTemplateBackColor;
  75. }
  76. dgvcombo.DefaultCellStyle.ForeColor = CellTemplateforeColor;
  77. ShanuDGV.Columns.Add(dgvcombo);
  78. break;
  79. case ShanuControlTypes.Button:
  80. DataGridViewButtonColumn dgvButtons = new DataGridViewButtonColumn();
  81. dgvButtons.Name = cntrlnames;
  82. dgvButtons.FlatStyle = FlatStyle.Popup;
  83. dgvButtons.DataPropertyName = cntrlnames;
  84. dgvButtons.HeaderText = Headertext;
  85. dgvButtons.ToolTipText = ToolTipText;
  86. dgvButtons.Visible = Visible;
  87. dgvButtons.Width = width;
  88. dgvButtons.SortMode = DataGridViewColumnSortMode.Automatic;
  89. dgvButtons.Resizable = Resizable;
  90. dgvButtons.DefaultCellStyle.Alignment = cellAlignment;
  91. dgvButtons.HeaderCell.Style.Alignment = headerAlignment;
  92. if (CellTemplateBackColor.Name.ToString() != "Transparent") {
  93. dgvButtons.CellTemplate.Style.BackColor = CellTemplateBackColor;
  94. }
  95. dgvButtons.DefaultCellStyle.ForeColor = CellTemplateforeColor;
  96. ShanuDGV.Columns.Add(dgvButtons);
  97. break;
  98. case ShanuControlTypes.ImageColumn:
  99. DataGridViewImageColumn dgvnestedBtn = new DataGridViewImageColumn();
  100. dgvnestedBtn.Name = cntrlnames;
  101. dgvnestedBtn.Image = Image.FromFile("shanu.JPG"); //global::ShanuDGVHelper_Demo.Properties.Resources.toggle;
  102. dgvnestedBtn.HeaderText = Headertext;
  103. dgvnestedBtn.ToolTipText = ToolTipText;
  104. // dgvnestedBtn.DataPropertyName = cntrlnames;
  105. dgvnestedBtn.Visible = Visible;
  106. dgvnestedBtn.Width = width;
  107. dgvnestedBtn.SortMode = DataGridViewColumnSortMode.Automatic;
  108. dgvnestedBtn.Resizable = Resizable;
  109. dgvnestedBtn.DefaultCellStyle.Alignment = cellAlignment;
  110. dgvnestedBtn.HeaderCell.Style.Alignment = headerAlignment;
  111. ShanuDGV.Columns.Add(dgvnestedBtn);
  112. break;
  113. }
  114. }

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

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

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