情景:在winform的dataGridView 中一个Column中显示两个按钮,本文将提及以下三种形式。
- 在一列中使用两个文字形式的按钮,得到的结果如下图的“Action”列。
- 在一列中显示两张按钮图片,得到的结果如下图的“Order First”列。
- 将按钮图标放在相邻的两列,合并标题,得到的结果如下图的“Order”列。
一.在一列中使用两个文字形式的按钮
注:参考文章https://www.cnblogs.com/aijiao/p/10038483.html
在datagridview的CellPainting事件中绘制两个文字按钮,写入如下代码:
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
{
if (this.dataGridView1.Columns[e.ColumnIndex].Name == "Action")
{
//set font style
StringFormat stringFormat = StringFormat.GenericDefault.Clone() as StringFormat;
stringFormat.FormatFlags = StringFormatFlags.DisplayFormatControl;
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Center;
stringFormat.Trimming = StringTrimming.EllipsisCharacter;
e.PaintBackground(e.CellBounds, false);
System.Drawing.Font font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
SizeF sizeDel = e.Graphics.MeasureString("Delete", font);
SizeF sizeLook = e.Graphics.MeasureString("Detail", font);
float fDel = sizeDel.Width / (sizeDel.Width + sizeLook.Width);
float fLook = sizeLook.Width / (sizeDel.Width + sizeLook.Width);
RectangleF rectDel = new RectangleF(e.CellBounds.Left, e.CellBounds.Top, e.CellBounds.Width * fDel, e.CellBounds.Height);