Technical summary: WinForm DataGridView operation column of C

Time:2021-2-23

DataGridView in WinForm framework is the same as table in HTML.

But the difference is that there is no concept of operation column in the native DataGridView. The default column types are drop-down box, text, button, picture and link. If you need other styles, you need to rewrite them.

In fact, most of the requirements are as shown in the figure. Of course, if you use other components [not official ones], it may be very easy to achieve the effect as shown in the figure

Technical summary: WinForm DataGridView operation column of C

As shown in the figure below, the operation column has different implementation modes of multiple buttons

1.1 mode 1

using System;using  System.Collections.Generic ;using  System.ComponentModel ;using  System.Data ;using  System.Drawing ;using  System.Linq ;using  System.Text ;using  System.Threading.Tasks ;using  System.Windows.Forms ; namespace  chao.net {    public partial class FormTest2 : Form    {        public FormTest2()        {            InitializeComponent();        }          private void toolStripLabel1_ Click(object sender, EventArgs e)        {         }         private void FormTest2_ Load(object sender, EventArgs e)        {             this.dataGridView1 .AutoGenerateColumns = false;;             this.dataGridView1 .CellMouseClick += dataGridView1_ CellMouseClick;             this.dataGridView1 .CellPainting += dataGridView1_ CellPainting;             this.dataGridView1 . Rows.Add ();} // / < summary > // / cell redrawing // / < / summary > // < param name = "sender" > < / param > // < param name = "e" > < / param > private void datagridview1_ CellPainting(object sender, DataGridViewCellPaintingEventArgs e)        {            if (e.ColumnIndex >= 0 && e.RowIndex >= 0)            {                if ( this.dataGridView1 . columns [e.columnindex]. Headertext = = = operation ") {stringformat SF= StringFormat.GenericDefault.Clone () as StringFormat; //Sets the font style for redrawn cells sf.FormatFlags  =  StringFormatFlags.DisplayFormatControl ;                     sf.Alignment  =  StringAlignment.Center ;                     sf.LineAlignment  =  StringAlignment.Center ;                     sf.Trimming  =  StringTrimming.EllipsisCharacter ;                     //e.PaintContent         e. Paintbackground (e.cellboundaries, false); // redraw the border // set the size of the font to be written System.Drawing.Font  myFont = new  System.Drawing.Font (Microsoft YaHei, 9F, System.Drawing.FontStyle .Underline,  System.Drawing.GraphicsUnit .Point, ((byte)(134)));                     //myFon                     SizeF sizeDel = e. Graphics.MeasureString ("delete", myfont); sizef sizemod = E Graphics.MeasureString ("modify", myfont); sizefsizelook = E Graphics.MeasureString ("view", myfont); float fdel= sizeDel.Width  / ( sizeDel.Width  +  sizeMod.Width  +  sizeLook.Width ); //                     float fMod =  sizeMod.Width  / ( sizeDel.Width  +  sizeMod.Width  +  sizeLook.Width );                    float fLook =  sizeLook.Width  / ( sizeDel.Width  +  sizeMod.Width  +  sizeLook.Width ); // set rectangle f rectdel = new rectangle f (e CellBounds.Left , e. CellBounds.Top ,  e. CellBounds.Width  * fDel, e. CellBounds.Height );                     RectangleF rectMod = new RectangleF( rectDel.Right , e. CellBounds.Top , e. CellBounds.Width  * fMod, e. CellBounds.Height );                     RectangleF rectLook = new RectangleF( rectMod.Right , e. CellBounds.Top , e. CellBounds.Width  * fLook, e. CellBounds.Height );                      e. Graphics.DrawString (delete, myfont, Brushes.Black , rectdel, SF); // draw "button" E Graphics.DrawString (modify, myfont, Brushes.Black , rectMod, sf);                    e. Graphics.DrawString (view, myfont, Brushes.Black , rectLook, sf);                     e.Handled = true;                }            }         }      ///< summary > // / mouse click events // / < / summary > // < param name = "sender" > < / param > // < param name = "e" > < / param > private void datagridview1_ Cellmouseclick (object sender, datagridviewcellmouseeventargs E) {if (e.columnindex > = 0 & & e.rowindex > = 0) {point curposition = e.location; // if the current mouse coordinates in the current cell( this.dataGridView1 . columns [e.columnindex]. Headertext = = operation){    // this.dataGridView1 .Columns[e.ColumnIndex].Add                     Graphics g =  this.dataGridView1 .CreateGraphics();                     System.Drawing.Font  myFont = new  System.Drawing.Font (Song Ti, 9F, System.Drawing.FontStyle .Underline,  System.Drawing.GraphicsUnit .Point, ((byte)(134)));                     Sizefsizedel = g.measurestring ("delete", myfont); sizefsizemod = g.measurestring ("modify", myfont); sizefsizelook = g.measurestring ("view", myfont); float fdel= sizeDel.Width  / ( sizeDel.Width  +  sizeMod.Width  +  sizeLook.Width );                     float fMod =  sizeMod.Width  / ( sizeDel.Width  +  sizeMod.Width  +  sizeLook.Width );                    float fLook =  sizeLook.Width  / ( sizeDel.Width  +  sizeMod.Width  +  sizeLook.Width );                     Rectangle rectTotal = new Rectangle(0, 0,  this.dataGridView1 .Columns[e.ColumnIndex].Width,  this.dataGridView1 .Rows[e.RowIndex].Height);                     RectangleF rectDel = new RectangleF( rectTotal.Left ,  rectTotal.Top ,  rectTotal.Width  * fDel,  rectTotal.Height );                    RectangleF rectMod = new RectangleF( rectDel.Right ,  rectTotal.Top ,  rectTotal.Width  * fMod,  rectTotal.Height );                    RectangleF rectLook = new RectangleF( rectMod.Right ,  rectTotal.Top ,  rectTotal.Width  * fLook,  rectTotal.Height ); // determine which button the current mouse is in( rectDel.Contains (curposition)) // delete MessageBox.Show (click the delete button); else if ( rectMod.Contains (curposition)) // modify MessageBox.Show (click Modify button); else if( rectLook.Contains (curposition)) // view MessageBox.Show (click View button);}}}} private void datagridview1_ CellContentClick(object sender, DataGridViewCellEventArgs e)        {         }    }}

The main method is: datagridview1_ Cellpainting is to redraw cells. The code is in formtest2. CS, and the entry link is at the bottom.

effect:

Technical summary: WinForm DataGridView operation column of CTechnical summary: WinForm DataGridView operation column of C

1.2 mode 2

Right click menu = =, or click the button in the line to display the menu. [learn to draw inferences from one instance]

using System;using  System.Collections.Generic ;using  System.ComponentModel ;using  System.Data ;using  System.Drawing ;using  System.Linq ;using  System.Text ;using  System.Threading.Tasks ;using  System.Windows.Forms ; namespace  chao.net {    public partial class FormTest3 : Form    {        public FormTest3()        {            InitializeComponent();         }         private void FormTest3_ Load(object sender, EventArgs e)        {             this.dataGridView1 .AutoGenerateColumns = false; ;             this.dataGridView1 .MouseClick += dataGridView1_ MouseClick;             this.dataGridView1 . Rows.Add ();} // / < summary > // / stripitem0 click event - delete selected line // / < / summary > private void stripitems0_ Click(object sender, EventArgs e)        {             MessageBox.Show ("- delete selected line --);} private void datagridview1_ MouseClick(object sender, MouseEventArgs e)        {            ContextMenuStrip strip = new ContextMenuStrip();             strip.ShowImageMargin  =False; // set the right-click menu properties strip.Items.Add (delete selected row)); strip.Items.Add ("Add Row"); strip.Items [0].Click += stripItems0_ Click; // the first click event in the pop-up menu strip.Items [1].Click += stripItems1_ Click; // click the event if (e.button) in the second item of the pop-up menu== MouseButtons.Right )//Right click{ strip.Show ( this.dataGridView1 , e.location); // pop up menu}} // / < summary > // / pop up menu second click event // / < summary > private void stripitems1_ Click(object sender, EventArgs e)        {             MessageBox.Show ("- add line -");}

Explanation: the main method is: datagridview1_ MouseClick, here to determine whether to right-click [please right-click in DataGridView]. The code is in formtest3. CS, and the entry link is at the bottom. [in fact, this kind of thinking is more suitable for the client. There are differences between web page and desktop application]

effect:

Technical summary: WinForm DataGridView operation column of C

Technical summary: WinForm DataGridView operation column of C

1.3 mode 3

It’s a dynamic operation column written by me referring to some inherent styles on the Internet, which is suitable for permission management [button]. Recommended. Of course, there may be some small problems. I haven’t found them yet. This style is similar to the operation column of back-end management. If the button exceeds the width of the column, set the appropriate width of the column.

using  chao.net.UIL ;using  chao.net.UIL .UserControls;using System;using  System.Collections.Generic ;using  System.ComponentModel ;using  System.Data ;using  System.Drawing ; using  System.Linq ;using  System.Text ;using  System.Threading.Tasks ;using  System.Windows.Forms ;  namespace  chao.net {    public partial class FormTest : Form    {                   public FormTest()        {            InitializeComponent();        }         private void FormTest_ Load(object sender, EventArgs e)        {                    this.dataGridView1 .AutoGenerateColumns = false;              DataGridViewActionButtonColumn dataGridViewColumn = new DataGridViewActionButtonColumn();             dataGridViewColumn.Width  = 240;             dataGridViewColumn.HeaderText  =Operation column 2; dataGridViewColumn.Resizable  =  DataGridViewTriState.False ;             this.dataGridView1 . Columns.Add (dataGridViewColumn); /*            DataGridViewDetailButtonColumn buttonColumn = new DataGridViewDetailButtonColumn();             buttonColumn.HeaderText  =Operation column 3; this.dataGridView1 . Columns.Add (buttonColumn); */              this.dataGridView1 . Rows.Add ();           /*  this.dataGridView1 .RowHeadersVisible = true;             this.dataGridView1 .ColumnHeadersVisible = true;*/         }             private void dataGridView1_ CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)        {             if ( this.dataGridView1 . columns [e.columnindex]. Headertext = = operation column 2 ") {datagridviewactionbuttoncolumn datagridviewcolumn = (datagridviewactionbuttoncolumn) this.dataGridView1 .Columns[e.ColumnIndex];                  //DataGridViewActionButtonCell dataGridViewActionButtonCell = (DataGridViewActionButtonCell) dataGridViewColumn.CellTemplate ;                 List<ActionButton> buttonList =  dataGridViewColumn.ButtonList ;                 foreach(ActionButton act in buttonList){                    if ( act.MouseOnButton )//At this time, the mouse hovers over it   {                         Console.WriteLine (click:+ act.Name );                        // MessageBox.Show (click:+ act.Name );                    }                }                       }         }      }}

Explanation: the main method is: formtest_ Load and datagridview1_ MouseClick,FormTest_ Load is mainly a custom cell, datagridview1_ MouseClick is the button area that you click to judge the click, and then do business. You need to use custom columnsDataGridViewActionButtonColumnAnd custom cellsDataGridViewActionButtonCell。Code in FormTest.cs Inside, the access link is at the bottom. [in fact, this kind of thinking is more suitable for the client. There are differences between web page and desktop application]

effect:

Technical summary: WinForm DataGridView operation column of C

Technical summary: WinForm DataGridView operation column of C

Technical summary: WinForm DataGridView operation column of C

Source code:https://gitee.com/ten-ken/csharp-demo-code/tree/master/chao.net

[temporarily closed to the outside world, waiting for a while]

This article comes from: Song Wenchao super, exclusive platforms are CSDN, segment fault, Jianshu, open source China, please indicate the source of reprint.