Winform DataGridView列的单元格中动态添加图片和文字

时间:2022-04-24 14:47:01

先上图在说,第二列中图片和文字的样式

Winform DataGridView列的单元格中动态添加图片和文字

1、需要重写DataGridViewTextBoxColumn,新建类TextAndImageColumn.cs

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing; namespace DataGridViewTest
{
public class TextAndImageColumn : DataGridViewTextBoxColumn
{
private Image imageValue;
private Size imageSize; public TextAndImageColumn()
{
this.CellTemplate = new TextAndImageCell();
} public override object Clone()
{
TextAndImageColumn c = base.Clone() as TextAndImageColumn;
c.imageValue = this.imageValue;
c.imageSize = this.imageSize;
return c;
} public Image Image
{
get { return this.imageValue; }
set
{
if (this.Image != value)
{
this.imageValue = value;
this.imageSize = value.Size; if (this.InheritedStyle != null)
{
Padding inheritedPadding = this.InheritedStyle.Padding;
this.DefaultCellStyle.Padding = new Padding(imageSize.Width,
inheritedPadding.Top, inheritedPadding.Right,
inheritedPadding.Bottom);
}
}
}
}
private TextAndImageCell TextAndImageCellTemplate
{
get { return this.CellTemplate as TextAndImageCell; }
}
internal Size ImageSize
{
get { return imageSize; }
}
} public class TextAndImageCell : DataGridViewTextBoxCell
{
private Image imageValue;
private Size imageSize; public override object Clone()
{
TextAndImageCell c = base.Clone() as TextAndImageCell;
c.imageValue = this.imageValue;
c.imageSize = this.imageSize;
return c;
} public Image Image
{
get
{
if (this.OwningColumn == null ||
this.OwningTextAndImageColumn == null)
{ return imageValue;
}
else if (this.imageValue != null)
{
return this.imageValue;
}
else
{
return this.OwningTextAndImageColumn.Image;
}
}
set
{
if (this.imageValue != value)
{
this.imageValue = value;
this.imageSize = value.Size; Padding inheritedPadding = this.InheritedStyle.Padding;
this.Style.Padding = new Padding(imageSize.Width,
inheritedPadding.Top, inheritedPadding.Right,
inheritedPadding.Bottom);
}
}
}
protected override void Paint(Graphics graphics, Rectangle clipBounds,
Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState,
object value, object formattedValue, string errorText,
DataGridViewCellStyle cellStyle,
DataGridViewAdvancedBorderStyle advancedBorderStyle,
DataGridViewPaintParts paintParts)
{
// Paint the base content
base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState,
value, formattedValue, errorText, cellStyle,
advancedBorderStyle, paintParts); if (this.Image != null)
{
// Draw the image clipped to the cell.
System.Drawing.Drawing2D.GraphicsContainer container =
graphics.BeginContainer(); graphics.SetClip(cellBounds);
graphics.DrawImageUnscaled(this.Image, cellBounds.Location); graphics.EndContainer(container);
}
} private TextAndImageColumn OwningTextAndImageColumn
{
get { return this.OwningColumn as TextAndImageColumn; }
}
}
}

2、新建窗体Form1.cs,拖控件DataGridView到窗体,代码如下

 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;
using System.Data.SqlClient; namespace DataGridViewTest
{
public partial class Form1 : Form
{
private static string imagePath = AppDomain.CurrentDomain.BaseDirectory.Substring(, AppDomain.CurrentDomain.BaseDirectory.IndexOf("bin")) + "Images\\";//列表图片路径
public Form1()
{
InitializeComponent();
InitControlsProperties();
} private void InitControlsProperties()
{
this.dataGridView1.AutoGenerateColumns = false;
TextAndImageColumn ColumnRoleID = new TextAndImageColumn();
ColumnRoleID.DataPropertyName = "RoleID";
ColumnRoleID.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
ColumnRoleID.Name = "RoleID";
ColumnRoleID.HeaderText = "权限ID";
ColumnRoleID.Width = ;
this.dataGridView1.Columns.Add(ColumnRoleID); this.dataGridView1.AutoGenerateColumns = false;
TextAndImageColumn ColumnRoleName = new TextAndImageColumn();
ColumnRoleName.DataPropertyName = "RoleName";
ColumnRoleName.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
ColumnRoleName.Name = "RoleName";
ColumnRoleName.HeaderText = "权限名称";
ColumnRoleName.Width = ;
this.dataGridView1.Columns.Add(ColumnRoleName); this.dataGridView1.AutoGenerateColumns = false;
TextAndImageColumn ColumnDescription = new TextAndImageColumn();
ColumnDescription.DataPropertyName = "Description";
ColumnDescription.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
ColumnDescription.Name = "Description";
ColumnDescription.HeaderText = "描述";
ColumnDescription.Width = ;
this.dataGridView1.Columns.Add(ColumnDescription);
} private void Form1_Load(object sender, EventArgs e)
{
string strConn = "Data Source=XIAN-PC;Initial Catalog=ReportServer;Persist Security Info=True;User ID=sa;Password=sa";
SqlConnection conn = new SqlConnection(strConn);
string strSql = "select * from Roles";
SqlCommand cmd = new SqlCommand(strSql, conn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
conn.Open();
adapter.Fill(ds, "Roles");
conn.Close();
this.dataGridView1.DataSource = ds.Tables["Roles"];
} private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
#region 第二列
if (e.ColumnIndex == )
{
TextAndImageCell cell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex] as TextAndImageCell;
if (cell != null && e.Value != null)
{
try
{
string ajzt = cell.Value.ToString();
string path = imagePath;
switch (ajzt)
{
case "发布者":
path += "1.png";
break;
case "浏览者":
path += "2.png";
break;
default:
path += "3.png";
break;
}
cell.Image = GetImage(path);
}
catch (Exception ex)
{ }
}
}
#endregion
} public System.Drawing.Image GetImage(string path)
{
return System.Drawing.Image.FromFile(path);
} }
}