1. Commonly used attributes
  • CurrentCell properties

Gets or sets the currently active cell. Syntax: public DataGridViewCell currentCell{get; set; }

The default is the first cell in the first column, or empty reference if there are no cells in the control.

Example: DataGridView1 CurrentCell = DataGridView1 [0, 0];

Cancel selected by default the method 1, dataGridView1. CurrentCell = null;

  1. dataGridView1.ClearSelection();
  2. dataGridView1.Row[0].Selected=false;
  • SelectionMode property

Gets or sets a value for how to select the cells of the DataGridView. Is one of the enumeration values of DataGridViewSelectionMode.

CellSelect You can select one or more cells.
ColumnHeaderSelect You can select this column by clicking its header cell. You can select a cell individually by clicking on it.
FullColumnSelect Select the entire column by clicking its header or the cell that the column contains.
FullRowSelect Select the entire row by clicking the row header or the cell that the row contains.
RowHeaderSelect Select the row by clicking the row header cell. You can select a cell individually by clicking on it.

Set the DataGridView property SelectionMode to FullRowSelect

This makes the DataGridView select an entire row instead of a single field

  • AllowUserToAddRows properties

Gets or sets a value indicating whether the option to add rows is displayed to the user.

True if the Add Row option is displayed to the user; Remove the default and add a new row to false

  • FirstDisplayedScrollingRowIndex properties

Get or set a row index, the bank is displayed in the System. Windows. Forms. The first line of the DataGridView.

The DataGridView line is visible:

int rowIndex=DataGridView1.SelectedRows[0].Index;

DataGridView1. FirstDisplayedScrollingRowIndex=rowIndex;

  • CurrentCellAddress properties

Gets or sets the rows and columns of the current cell. The CurrentCell of the DataGridView, which can be retrieved from the CurrentCell property of the DataGridView. Using CurrentCellAddress to determine the cell lines in DataGridView. CurrentCellAdress. Y and column: DataGridView. CurrentCellAdress. X.

  • DefaultCellStyle properties

Gets or sets the default cell style applied to cells in the DataGridView without setting other cell style properties. Style a single line:

dataGrid.Row[2]. DefaultCellStyle.BackColor=Color.Green;

DataGrid. Row [2]. DefaultCellStyle. The Font = new System. Drawing. The Font (” tahoma “, 9, System. Drawing. FontStyle. Strikeout).

  • RowHeadersVisible properties

Gets or sets a value indicating whether the header is visible.

  • AutoGenerateColumns attribute

Get or set a value, the value indicator in setting System. Windows. Forms. The DataGridView. The DataSource or System. Windows. Forms. The DataGridView. DataMember attribute is automatically created.

True if columns should be created automatically; Otherwise, it is false. The default value is true.

  • AllowUserToResizeColumns properties

Gets or sets a value indicating whether the user can resize the column.

  • AllowUserToResizeRows properties

Gets or sets a value indicating whether a user can resize a row.

  1. Common event
  • CurrentCellDirtyStateChanged event

When the contents of a cell have changed, but the changes have not been saved, the cell is marked as modified. This event usually occurs when the cell has been edited, but the changes have not been committed to the data cache, or when the edit operation has been canceled.

In CurrentCellDirtyStateChanged event handlers call CommitEdit method to trigger CellValueChanged events. DataGridView cannot respond to Combobox value changes in a timely manner.

private void dataGridView1_ColumnDefaultCellStyleChanged(object sender, DataGridViewColumnEventArgs e)

        {

            if (this.dataGridView1.IsCurrentCellDirty == true)

            {

                this.dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);

            }

        }

Add the above code to achieve CellValueChanged event when a cell changes

  • CellClick event

Occurs when any part of a cell is clicked.

Ex. :

    private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)

    {

       string aa = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();

}

  • CellValueChanged event

The values specified in the user submit the DataGridView. Occurs when CellValueChanged event, is usually happen in focus when you leave the cell.

But with checkbox cells, you usually want to process the changes right away. To cells and click the submit changes, must deal with DataGridView. CurrentCellDirtyStateChanged events. In the handler, if the current cell is a checkbox cell, the datagridview.mitEdit method is called and the Commit value is passed in.

Rows in the control are not automatically sorted when you change the value of a cell. To Sort the control as the user modifies the cell, call the Sort method in the CellValueChanged event handler.

  1. Using an example
  • DataGridView Uncheck the default selected row.

        DataGridView1.ClearSelection();

or

dataGridView1.CurrentCell=null;

or

dataGridView1.Row[0].Selected=false;

  • Implement a column to enter only numbers

Recently, when I was developing a project, I required that only numbers could be entered in one column and other characters could not be accepted. Microsoft did not provide this function.

Can only use their own code to achieve, on the Internet to find, most of the input after the completion of the verification. Unfortunately, my code can block non-numeric characters as they are typed in. This is done primarily in the EditingControlShowing event. Look at the code:

public DataGridViewTextBoxEditingControl CellEdit = null; // Declare a CellEdit

  private void datagridyf_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)  

        {  

CellEdit = (DataGridViewTextBoxEditingControl)e.Control; / / assignment

            CellEdit.SelectAll();  

CellEdit.KeyPress += Cells_KeyPress; // Bind to events

        }  

// Custom events

        private void Cells_KeyPress(object sender, KeyPressEventArgs e)  

        {  

If (datagridyf. CurrentCellAddress. X = = 2) / / whether the current column is to control the column I is to control the index value of 2 columns (i.e., the third column)

            {  

if ((Convert.ToInt32(e.KeyChar) < 48 || Convert.ToInt32(e.KeyChar) > 57) && Convert.ToInt32(e.KeyChar) ! = 46 && Convert.ToInt32(e.KeyChar) ! = 8 && Convert.ToInt32(e.KeyChar) ! = 13)

                {  

e.Handled = true; // If input is illegal, block it

                }  

                else 

                {  

                    if ((Convert.ToInt32(e.KeyChar) == 46) && (txtjg.Text.IndexOf(“.”) != -1))  

                    {  

                        e.Handled = true;  

                    }  

                }  

            }  

        }  

The following is validated only after the input is completed and this is mainly done in the CellValidating event

private void datagridyf_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)  

        {  

            if (e.ColumnIndex == datagridyf.Columns[“Pric”].Index )  

            {  

                datagridyf.Rows [e.RowIndex].ErrorText =””;  

                int NewVal=0;  

if (! int.TryParse (e.FormattedValue.ToString (),out NewVal ) || NewVal <0)

                {  

                    e.Cancel=true ;   

Datagridyf. Rows [e.rowindex].ErrorText =” Price column can only enter numbers “;

                    return ;  

                }  

            }  

        }   

  • Fixed the first two columns not scrolling with the scroll bar.

private void Form1_Load(object sender, EventArgs e)

        {

            dataGridView1.Columns[0].Frozen = true;

dataGridView1.Columns[1].Frozen = true; // Keep the first two columns in the same position when scrolling.

            for (int i = 0; i < 10; i++)

            {

                dataGridView1.Rows.Add(“11”, 2, 3, 4, 5, 6, 7, 7, 8, 8, 9, 9, 9);

            }

        }

  • Move a row up or down

/*DataGridView moves rows up and down. There is a reason why I use SelectedRows[0] instead of CurrentRow

These are the two main pieces of code:

   dataGridView1.Rows[rowIndex – 1].Selected = true;

   dataGridView1.Rows[rowIndex].Selected = false;

These two lines of code you should be able to understand, which line goes up to the selected state, and which line goes down to the unselected state.

If I use dataGridView1. CurrentRow. Cell [0]. The Value he earned Value is still rowIndex index Value

To use SelectedRows [0], you have to set this property: dataGridView1. SelectionMode = DataGridViewSelectionMode. FullRowSelect;

Implementation principle: is up and down two lines, the cell values exchange… Well, it seems to be moving up and down

* /

    private void Form3_Load(object sender, EventArgs e)

    {

/ /… The code to get the DataTable is omitted from….

/ / up

        private void btnMoveUp_Click(object sender, EventArgs e)

        {

// Select the line number

            int selectedRowIndex = GetSelectedRowIndex(this.dataGridView1);

            if (selectedRowIndex >= 1)

            {

// Copy the selected row

                DataGridViewRow newRow = dataGridView1.Rows[selectedRowIndex];

// Delete the selected row

                dataGridView1.Rows.Remove(dataGridView1.Rows[selectedRowIndex]);

// Insert the copied row into the position above the selected line

                dataGridView1.Rows.Insert(selectedRowIndex – 1, newRow);

// Select the originally selected row

                dataGridView1.Rows[selectedRowIndex – 1].Selected = true;

            }

        }

/ / move down

        private void btnMoveDown_Click(object sender, EventArgs e)

        {

            int selectedRowIndex = GetSelectedRowIndex(this.dataGridView1);

            if (selectedRowIndex < dataGridView1.Rows.Count-1)

            {

// Copy the selected row

                DataGridViewRow newRow = dataGridView1.Rows[selectedRowIndex];

// Delete the selected row

                dataGridView1.Rows.Remove(dataGridView1.Rows[selectedRowIndex]);

// Insert the copied row into the next selected row

                dataGridView1.Rows.Insert(selectedRowIndex + 1, newRow);

// Select the originally selected row

                dataGridView1.Rows[selectedRowIndex + 1].Selected = true;

            }

        }

// Get the row index number selected in the DataGridView

        private int GetSelectedRowIndex(DataGridView dgv)

        {

            if(dgv.Rows.Count==0)

            {

                return 0;

            }

           

            foreach(DataGridViewRow row in dgv.Rows)

            {

                if (row.Selected)

                {

                    return row.Index;

                }

            }

            return 0;

        }

// Display serial number, line number

        private void dataGridView1_RowPostPaint(object sender,DataGridViewRowPostPaintEventArgs e)

        {

            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,

                            e.RowBounds.Location.Y,

                            dataGridView1.RowHeadersWidth – 4,

                            e.RowBounds.Height);            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),

                dataGridView1.RowHeadersDefaultCellStyle.Font,rectangle,

                dataGridView1.RowHeadersDefaultCellStyle.ForeColor,

                TextFormatFlags.VerticalCenter | TextFormatFlags.Right);

        }         

Detects changes in cell values while the current active cell is in the edit state and retrieves values. (DataGridView is a composite control, there is no way to get the value in the edit state.)

  • Achieve the current active cell in the edit state to obtain cell value changes.

The first way:

private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)

        {

            if (this.dataGridView1.IsCurrentCellDirty == true)

            {

                this.dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);

            }

        }

        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)

        {

            MessageBox.Show(“aaaa”);

        }

The second way:

private void dgrMenuItem_EditingControlShowing(object sender,DataGridViewEditingControlShowingEventArgs e)

{

    if (e==null ||e.Control)

        return;

    e.Control.TextChanged+=new EventHander(Control_TextChanged);

}

void Control_TextChanged(object sender,EventArgs e)

{

MessageBox. Show (” ok “);

if (dgrMenItem.CurrentCellAdress.X==3)

{

        string val=dgrMenuItem.CurrentCell.EditedFormattedValue.ToString();

}

// Another way to get

Control txt=Sender as Control;

if (dgrMenItem.CurrentCellAdress.X==3)

{

    string val=txt.Text;

}

}

  • Use drop – down box to display data, can be modified to increase, validation repeated.

Set SelectionMode of DataGridView to FullRowSelect

Calls the event of the dropdown control using the EditingControlShowing event.

private bool isInit=false;

private void dgrdThridLangage_EditingControlShowing(object sender,DataGridViewEditingControlShowingEventArgs e)

{

if (e==null|| e.Control==null)

{

    return;

}

if (e.Control is ComboBox)

{

    ComboBox cmb=e.Control as ComboBox;

    cmb.SelectedIndexChanged+=new EventHander(cmb_SelectIndexChanged);

}

}

void cmb_SelectedIndexChanged(object sender,EventArgs e)

{

    if (isInit==true)

{

    return;

}

ComboBox result=sender as ComboBox;

if (! string.IsNullOrEmpty(relust.Text))

{

    string foreignName=relust.Text;

    if (plurDic.ContainsKey(foreignName))

{

Messagebox.show (” already exists, please change language “);

isInit=true; // Set the flag bit to prevent repeated execution from forming an endless loop.

    result.SelectedIndex=-1;

    isInit=false;

return;

}

}

}

  • Add a check box to the DatGridView header for full column selection and clarity.

 

   

public partial class Form1 : Form

    {

        CheckBox HeaderCheckBox = null;

        public Form1()

        {

            InitializeComponent();

if (! this.DesignMode)

            {

                HeaderCheckBox = new CheckBox();

                HeaderCheckBox.Size = new Size(15, 15);

                HeaderCheckBox.Text = “”;

                this.dataGridView1.Controls.Add(HeaderCheckBox);

                HeaderCheckBox.CheckedChanged += HeaderCheckBox_CheckedChanged;

                dataGridView1.CellPainting += DataGridView1_CellPainting;

            }

            AddData();

        }

        private void AddData()

        {

            for (int i = 0; i < 10; i++)

            {

                dataGridView1.Rows.Add(false, “2”, “3”, “4”);

            }

        }

        private void DataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)

        {

            if (e.RowIndex == -1 && e.ColumnIndex == 4)

            {

                ResetHeaderCheckBoxLocation(e.ColumnIndex, e.RowIndex);

            }

        }

        private void HeaderCheckBox_CheckedChanged(object sender, EventArgs e)

        {

            HeaderCheckBoxClick((CheckBox)sender);

        }

        private void HeaderCheckBoxClick(CheckBox checkBox)

        {

            foreach (DataGridViewRow row in dataGridView1.Rows)

            {

                ((DataGridViewCheckBoxCell)row.Cells[0]).Value = HeaderCheckBox.Checked;

            }

            dataGridView1.RefreshEdit();

        }

        private void ResetHeaderCheckBoxLocation(int columnIndex, int rowIndex)

        {

            Rectangle rectangle = this.dataGridView1.GetCellDisplayRectangle(columnIndex, rowIndex, true);

            Point point = new Point(rectangle.Location.X + 3, rectangle.Location.Y + 3);

            HeaderCheckBox.Location = point;

        }

    }

}

  • Bind data to the drop-down column

 

Create a global set of dictionary types, place the data in the set, Name as the dictionary key, ID as the dictionary value, and add Name to the column.

       Dictionary<string, string> dic = new Dictionary<string, string>();

       

        private void button1_Click(object sender, EventArgs e)

        {

            dic.Add(“AA”, “OA”);

            dic.Add(“BB”, “HH”);

            DataGridViewComboBoxColumn cmbDep = (DataGridViewComboBoxColumn)dataGridView1.Columns[0];

            foreach (string name in dic.Keys)

            {

if (! cmbDep.Items.Contains(name))

                {

                    cmbDep.Items.Add(name);

                }

            }

        }

  • The DataGridView cell is validated and the focus does not leave after validation errors

Ideas:

Cell validation uses the CellValidating event. Call e.canel =true if the verification fails; Terminates the chain of events and hopefully will remain edited.

Call the DataGridView. CancelEdit; You can roll back the contents of a cell to the value before the modification. Using System. Windows. Forms. SendKey. Send (” ^ a “); Select all the contents of the cell.

Code:

private void dataGridView1_CellValidating(object sender,DataGridViewCellValidatingEventArgs e)

{

         if (e.RowIndex<0)

                   return;

if (e.ColumnIndex! = 2)

return; // Columns that are not validated are not executed

         bool isTrue=false;

// Validate logic

If (b==false)// indicates that the authentication failed

{

Messagebox.show (” not validated “);

         e.Cancel=true;

         dataGridView1.CancelEdit();

         dataGridView1.CurrentCell=dataGridView1[e.ColumnIndex,e.RowIndex];

         dataGridView1.BeginEdit(false);

}

}

  • Operate on the Button column in the DataGridView

private void dataGridView1_CellContentClick(object sender,DataGridViewCellEventArgs e)

{

         if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].GetType()==typeof(DataGridViewButtonCell))

{dataGridView1.Rows.RemoveAt(e.RowIndex); }

}

  • Convert a DataGridView to a DataTable

The DataSource of the DataGridView is a DataTable

The following method is used when the DataGridView traverses the data in the DataGridView, when there is no Datasource or when the Datasource is not of type DataTable.

  public System.Data.DataTable GetDataTable(DataGridView dataGridView)

        {

            System.Data.DataTable dt = new System.Data.DataTable();

            for (int count = 0; count < dataGridView.ColumnCount; count++)

            {

                DataColumn dataColumn = new DataColumn(dataGridView1.Columns[count].Name.ToString());

                dt.Columns.Add(dataColumn);

            }

            for (int count = 0; count < dataGridView1.Columns.Count; count++)

            {

                DataRow dr = dt.NewRow();

                for (int countsub = 0; countsub < dataGridView.Columns.Count; countsub++)

                {

                    dr[countsub] = Convert.ToString(dataGridView.Rows[count].Cells[countsub].Value);

                }

                dt.Rows.Add(dr);

            }

            return dt;

        }

  • The data moves up and down with the roller of the mouse.

The event used is the MouseWheel event.

dataGridView.MouseWheel+=new MouseEventHandler(dataGridView_MouseWheel);

dataGridView.TabIndex=0;

void dataGridView_MouseWheel(object sender,MouseEventArgs e)

{

         if (dataGridView.RowCount>dataGridView.DisplayRowCount(false))

{

         int index=dataGridView.FirstDisplayScrollingRowIndex;

         if (e.Delta>0)

         {

                   if (index>0)

                   {

                            dataGridView.FirstDisplayScrollingRowIndex=index-1;

}

}

else

{

         if(index<dataGridView.Row.Count-1)

         {

                   dataGridView.FirstDisplayScrollingRowIndex=index+1;

}

}

}

}

  • Multidimensional header

 

Create a new component and write TreeHeadDatagridView.cs

using System;

using System.ComponentModel;

using System.Collections.Generic;

using System.Diagnostics;

using System.Text;

using System.Windows.Forms;

using System.Collections;

using System.Drawing;

 

namespace CellPaintingDataGridView

{

    public partial class TreeHeadDataGridView : DataGridView

    {

        private TreeView treeView1=new TreeView();

        public TreeHeadDataGridView()

        {

            InitializeComponent();

        }

        public TreeHeadDataGridView(IContainer container)

        {

            container.Add(this);

            InitializeComponent();

        }

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]

        public TreeNodeCollection HeadSource

        {

            get { return this.treeView1.Nodes; }

        }

        private int _cellHeight = 17;

        private int _columnDeep = 1;

[Description(” Set or get depth of merged table header tree “)]

        public int ColumnDeep

        {

            get

            {

                if (this.Columns.Count == 0)

                    _columnDeep = 1;

                this.ColumnHeadersHeight = _cellHeight * _columnDeep;

                return _columnDeep;

            }

            set

            {

                if (value < 1)

                    _columnDeep = 1;

                else

                    _columnDeep = value;

                this.ColumnHeadersHeight = _cellHeight * _columnDeep;

            }

        }

        ///<summary>

/// draw the merge header

        ///</summary>

//<param name=”node”>

//<param name=”e”>

<param name=”level”> </param>

        ///<remarks></remarks>

        public void PaintUnitHeader(TreeNode node, DataGridViewCellPaintingEventArgs e, int level)

        {

// Exit the recursive call when the root node

            if (level == 0)

                return;

            RectangleF uhRectangle;

            int uhWidth;

            SolidBrush gridBrush = new SolidBrush(this.GridColor);

            Pen gridLinePen = new Pen(gridBrush);

            StringFormat textFormat = new StringFormat();

            textFormat.Alignment = StringAlignment.Center;

            uhWidth = GetUnitHeaderWidth(node);

// It differs from the original paste algorithm here.

            if (node.Nodes.Count == 0)

            {

                uhRectangle = new Rectangle(e.CellBounds.Left,

                            e.CellBounds.Top + node.Level * _cellHeight,

                            uhWidth – 1,

                            _cellHeight * (_columnDeep – node.Level) – 1);

            }

            else

            {

                uhRectangle = new Rectangle(

                            e.CellBounds.Left,

                            e.CellBounds.Top + node.Level * _cellHeight,

                            uhWidth – 1,

                            _cellHeight – 1);

            }

            Color backColor = e.CellStyle.BackColor;

if (node.BackColor ! = Color.Empty)

            {

                backColor = node.BackColor;

            }

            SolidBrush backColorBrush = new SolidBrush(backColor);

/ / draw a rectangle

            e.Graphics.FillRectangle(backColorBrush, uhRectangle);

/ / draw the bottom line

            e.Graphics.DrawLine(gridLinePen

                                , uhRectangle.Left

                                , uhRectangle.Bottom

                                , uhRectangle.Right

                                , uhRectangle.Bottom);

// Draw the right line

            e.Graphics.DrawLine(gridLinePen

                                , uhRectangle.Right

                                , uhRectangle.Top

                                , uhRectangle.Right

                                , uhRectangle.Bottom);

Write field text

            Color foreColor = Color.Black;

if (node.ForeColor ! = Color.Empty)

            {

                foreColor = node.ForeColor;

            }

            e.Graphics.DrawString(node.Text, this.Font

                                    , new SolidBrush(foreColor)

                                    , uhRectangle.Left + uhRectangle.Width / 2 –

                                    e.Graphics.MeasureString(node.Text, this.Font).Width / 2 – 1

                                    , uhRectangle.Top +

                                    uhRectangle.Height / 2 – e.Graphics.MeasureString(node.Text, this.Font).Height / 2);

Recursive call ()

            if (node.PrevNode == null)

if (node.Parent ! = null)

                    PaintUnitHeader(node.Parent, e, level – 1);

        }

        /// <summary>

/// get the width of the merged title field

        /// </summary>

<param name=”node”> </param>

/// <returns>

        /// <remarks></remarks>

        private int GetUnitHeaderWidth(TreeNode node)

        {

// Get the width of the non-lowest level field

            int uhWidth = 0;

// Get the width of the bottom field

            if (node.Nodes == null)

                return this.Columns[GetColumnListNodeIndex(node)].Width;

            if (node.Nodes.Count == 0)

                return this.Columns[GetColumnListNodeIndex(node)].Width;

            for (int i = 0; i <= node.Nodes.Count – 1; i++)

            {

                uhWidth = uhWidth + GetUnitHeaderWidth(node.Nodes[i]);

            }

            return uhWidth;

        }

        /// <summary>

/// get the underlying field index

        /// </summary>

<param name=”node”> </param>

// <returns> index </returns>

        /// <remarks></remarks>

        private int GetColumnListNodeIndex(TreeNode node)

        {

            for (int i = 0; i <= _columnList.Count – 1; i++)

            {

                if (((TreeNode)_columnList[i]).Equals(node))

                    return i;

            }

            return -1;

        }

        private List<TreeNode> _columnList = new List<TreeNode>();

[Description(” lowest node set “)]

        public List<TreeNode> NadirColumnList

        {

            get

            {

                if (this.treeView1 == null)

                    return null;

                if (this.treeView1.Nodes == null)

                    return null;

                if (this.treeView1.Nodes.Count == 0)

                    return null;

                _columnList.Clear();

                foreach (TreeNode node in this.treeView1.Nodes)

                {

                    //GetNadirColumnNodes(_columnList, node, false);

                    GetNadirColumnNodes(_columnList, node);

                }

                return _columnList;

            }

        }

        private void GetNadirColumnNodes(List<TreeNode> alList, TreeNode node)

        {

            if (node.FirstNode == null)

            {

                alList.Add(node);

            }

            foreach (TreeNode n in node.Nodes)

            {

                GetNadirColumnNodes(alList, n);

            }

        }

        /// <summary>

/// get the underlying set of fields

        /// </summary>

<param name=”alList”> </param>

<param name=”node”> </param>

// <param name=”checked”>

        /// <remarks></remarks>

        private void GetNadirColumnNodes(List<TreeNode> alList, TreeNode node, Boolean isChecked)

        {

            if (isChecked == false)

            {

                if (node.FirstNode == null)

                {

                    alList.Add(node);

if (node.NextNode ! = null)

                    {

                        GetNadirColumnNodes(alList, node.NextNode, false);

                        return;

                    }

if (node.Parent ! = null)

                    {

                        GetNadirColumnNodes(alList, node.Parent, true);

                        return;

                    }

                }

                else

                {

if (node.FirstNode ! = null)

                    {

                        GetNadirColumnNodes(alList, node.FirstNode, false);

                        return;

                    }

                }

            }

            else

            {

                if (node.FirstNode == null)

                {

                    return;

                }

                else

                {

if (node.NextNode ! = null)

                    {

                        GetNadirColumnNodes(alList, node.NextNode, false);

                        return;

                    }

if (node.Parent ! = null)

                    {

                        GetNadirColumnNodes(alList, node.Parent, true);

                        return;

                    }

                }

            }

        }

        /// <summary>

/// cell drawing (overwrite)

        /// </summary>

        /// <param name=”e”></param>

        /// <remarks></remarks>

        protected override void OnCellPainting(DataGridViewCellPaintingEventArgs e)

        {

// Line headings are not overwritten

            if (e.ColumnIndex < 0)

            {

                base.OnCellPainting(e);

                return;

            }

            if (_columnDeep == 1)

            {

                base.OnCellPainting(e);

                return;

            }

// Draw the header

            if (e.RowIndex == -1)

            {

                PaintUnitHeader((TreeNode)NadirColumnList[e.ColumnIndex], e, _columnDeep);

                e.Handled = true;

            }

        }

    }

}

You can then see the component you just wrote in the toolbox

 

Drag it into the form and click On HeadSource to add the header

 

    private void Form1_Load(object sender, EventArgs e)

    {

            TreeNode node=new TreeNode();

            node.Text=”wh”;

            treeHeadDataGridView1.HeadSource.Add(node);

     }

  • Add total row

Add Total row Support left and right drag row support mouse scroll.

 

Layout:

 

Ideas:

  1. The DataGridView in the data section does not have any scroll boxes
  2. The DataGridView for the aggregate section has a horizontal scroll box
  3. Add a vertical scroll box vscrollBar1 to the screen

The idea is to use the horizontal scroll box of the total row to control the horizontal scroll of the two DatagridViews. The vertical scroll box on the right controls the DataGridView of the data section. The effect is that the total row is always displayed at the bottom.

Page design:

  1. Put the DataGridView of the data display area and the data aggregate area into one DateGridView. The height of the total area is 40 pixels.
  2. DataGridView Settings for the data area:

DataGridView1.AllowUserToAddRows=False;

DataGridView1.ScroBars=None;

DataGridView1.SelectionMode=DataGridViewsSelectionMode.FullRowSelect;

DataGridView1.ColumnWidthChanged+=new DataGridViewColumnEventHandler(DataGridView1_ColumnWidthChanged);

  1. Data aggregation area Settings.

DataGridViewSum. AllowUserToAddRows=False;

DataGridViewSum.AllowUserToResizeColumns=False; // Columns cannot be dragged

DataGridViewSum.Anchor=Buttom,Left,Right;

DataGridViewSum.ColumnHeadersHeightSizeMode=System.Windows.Forms.DataGridViewColumnHeader.HeightSizeMode.AutoSize;

DataGridViewSum.ColumnsHeadersVisible=false;

DataGridViewSum.ReadOnly=true;

DataGridViewSum.ScrollBars=System.Windows.Forms.ScrollBars.Horizontal;

  1. VscrollBar1 control Settings

vscrollBar1.Anchor=Top,Button,Right;

this. vscrollBar1.visibleChanged+=new System.EventHander(vscrollBar1_VisibleChanged);

this. vscrollBar1.Scroll+=new System.Windows.Forms.ScrollEventHandler(vscrollBar1_Scroll);

Code:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

 

namespace WindowsFormsApplication11

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        private DataTable dt = new DataTable();

        private DataTable dtSum;

     

        private int Row_Height = 21;

        private void Form1_Load(object sender, EventArgs e)

        {

            VScrollBar1.Visible = false;

        }

        private void kButton1_Click(object sender, EventArgs e)

        {

            dt = GetData();

            this.kDataGridView1.AutoGenerateColumns = false;

            this.kDataGridView1.DataSource = dt;

            this.kDataGridView1.Columns[0].DataPropertyName = dt.Columns[0].ColumnName;

            this.kDataGridView1.Columns[1].DataPropertyName = dt.Columns[1].ColumnName;

            this.kDataGridView1.Columns[2].DataPropertyName = dt.Columns[2].ColumnName;

            this.kDataGridView1.Columns[3].DataPropertyName = dt.Columns[3].ColumnName;

            this.kDataGridView1.Columns[4].DataPropertyName = dt.Columns[4].ColumnName;

            this.kDataGridView1.Columns[5].DataPropertyName = dt.Columns[5].ColumnName;

            this.kDataGridView1.Columns[6].DataPropertyName = dt.Columns[6].ColumnName;

            this.kDataGridView1.Columns[7].DataPropertyName = dt.Columns[7].ColumnName;

            this.kDataGridView1.Columns[8].DataPropertyName = dt.Columns[8].ColumnName;

            this.kDataGridView1.Columns[9].DataPropertyName = dt.Columns[9].ColumnName;    

            this.kDataGridView1.RowTemplate.Height = Row_Height;

            GetSumData();

            if (kDataGridView1.RowCount > kDataGridView1.DisplayedRowCount(false))

            {

                VScrollBar1.Visible = true;

                VScrollBar1.Maximum = (this.kDataGridView1.Rows.Count – this.kDataGridView1.DisplayedRowCount(false)) * Row_Height;

                VScrollBar1.Minimum = 0;

                VScrollBar1.SmallChange = 21;

                VScrollBar1.LargeChange = 50;

            }

        }

        private DataTable GetData()

        {

            DataTable dtData = new DataTable(“TEST”);

           DataRow dr ;

Dt.columns.Add(new DataColumn(” number “, Typeof (String)));

Dt.columns.Add(new DataColumn(“数 据 1”, typeof(int)));

Dt.columns.Add(new DataColumn(“数 2”, typeof(int)));

Dt.columns.Add(new DataColumn(“数 据 3”, typeof(int)));

Dt.columns.Add(new DataColumn(“数 据 “, typeof(int)));

Dt.columns.Add(new DataColumn(“数 5”, typeof(int)));

Dt.columns.Add(new DataColumn(“数 据 6”, typeof(int)));

Dt.columns.Add(new DataColumn(“数 据 7”, typeof(int)));

Dt.columns.Add(new DataColumn(“数 据 8”, typeof(int)));

Dt.columns.Add(new DataColumn(“数 据 9”, typeof(int)));

            Random rdm = new Random();

            for (int i = 10; i < 80; i++)

            {

                dr = dt.NewRow();

                dr[0] = (“00” + i).ToString();

                for (int j = 1; j < 10; j++)

                {

                    dr[j] = rdm.Next(1000, 5000);

                }

                dt.Rows.Add(dr);

            }

            return dt;

        }

        private void GetSumData()

        {

            DataRow dr;

            dtSum = new DataTable(“TEST”);

            dtSum = dt.Clone();

            Random rdm = new Random();

            dr = dtSum.NewRow();

Dr [0] = “total “;

            for (int i = 1; i < dt.Columns.Count – 1; i++)

            {

                dr[i] = dt.Compute(“Sum(” + dt.Columns[i].ColumnName + “)”, “true”);

            }

            dtSum.Rows.Add(dr);

            this.kDataGridView2.AutoGenerateColumns = false;

            this.kDataGridView2.DataSource = dtSum;

            this.kDataGridView2.Columns[0].DataPropertyName = dtSum.Columns[0].ColumnName;

            this.kDataGridView2.Columns[1].DataPropertyName = dtSum.Columns[1].ColumnName;

            this.kDataGridView2.Columns[2].DataPropertyName = dtSum.Columns[2].ColumnName;

            this.kDataGridView2.Columns[3].DataPropertyName = dtSum.Columns[3].ColumnName;

            this.kDataGridView2.Columns[4].DataPropertyName = dtSum.Columns[4].ColumnName;

            this.kDataGridView2.Columns[5].DataPropertyName = dtSum.Columns[5].ColumnName;

            this.kDataGridView2.Columns[6].DataPropertyName = dtSum.Columns[6].ColumnName;

            this.kDataGridView2.Columns[7].DataPropertyName = dtSum.Columns[7].ColumnName;

            this.kDataGridView2.Columns[8].DataPropertyName = dtSum.Columns[8].ColumnName;

            this.kDataGridView2.Columns[9].DataPropertyName = dtSum.Columns[9].ColumnName;

            this.kDataGridView2.Rows[0].DefaultCellStyle.BackColor = Color.Red;

            this.kDataGridView2.ReadOnly = true;

            this.kDataGridView2.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

        }

        private void kDataGridView2_Scroll(object sender, ScrollEventArgs e)

        {

            this.kDataGridView1.HorizontalScrollingOffset = e.NewValue;

        }

        private void VScrollBar1_Scroll(object sender, ScrollEventArgs e)

        {

            this.kDataGridView1.FirstDisplayedScrollingRowIndex = e.NewValue / Row_Height ;

        }

        private void kDataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)

        {

           

        }

        private void kDataGridView1_RowHeadersWidthChanged(object sender, EventArgs e)

        {

         

        }

        private void kDataGridView1_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)

        {

            for (int i = 0; i < kDataGridView1.ColumnCount; i++)

            {

                kDataGridView2.Columns[i].Width = kDataGridView1.Columns[i].Width;

            }

        }

      

    }

}