다음을 통해 공유


DataGridView Helper Class

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. 

Building the Sample

Here is an sample with Color Dialog from button Column.

Description

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; 
            } 
        }

You can download the Source Code from this link Download Source Code