A DataGridView Helper

本文介绍了一个用于Windows表单应用程序中DataGridView的助手类。该类简化了DataGridView的设计与使用,包括动态创建DataGridView、设置样式、绑定数据及处理事件等。通过这个助手类,开发者可以更轻松地管理和操作DataGridView。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

1) Add the helperClass file in 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 the each column of your grid.

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.

This is from http://www.codeproject.com/Articles/841755/DataGridView-Helper-Class

Thanks CodeProject

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值