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

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

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

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.Windows.Forms;
  6 using System.Drawing;
  7 
  8 namespace DataGridViewTest
  9 {
 10     public class TextAndImageColumn : DataGridViewTextBoxColumn
 11     {
 12         private Image imageValue;
 13         private Size imageSize;
 14 
 15         public TextAndImageColumn()
 16         {
 17             this.CellTemplate = new TextAndImageCell();
 18         }
 19 
 20         public override object Clone()
 21         {
 22             TextAndImageColumn c = base.Clone() as TextAndImageColumn;
 23             c.imageValue = this.imageValue;
 24             c.imageSize = this.imageSize;
 25             return c;
 26         }
 27 
 28         public Image Image
 29         {
 30             get { return this.imageValue; }
 31             set
 32             {
 33                 if (this.Image != value)
 34                 {
 35                     this.imageValue = value;
 36                     this.imageSize = value.Size;
 37 
 38                     if (this.InheritedStyle != null)
 39                     {
 40                         Padding inheritedPadding = this.InheritedStyle.Padding;
 41                         this.DefaultCellStyle.Padding = new Padding(imageSize.Width,
 42                     inheritedPadding.Top, inheritedPadding.Right,
 43                     inheritedPadding.Bottom);
 44                     }
 45                 }
 46             }
 47         }
 48         private TextAndImageCell TextAndImageCellTemplate
 49         {
 50             get { return this.CellTemplate as TextAndImageCell; }
 51         }
 52         internal Size ImageSize
 53         {
 54             get { return imageSize; }
 55         }
 56     }
 57 
 58     public class TextAndImageCell : DataGridViewTextBoxCell
 59     {
 60         private Image imageValue;
 61         private Size imageSize;
 62 
 63         public override object Clone()
 64         {
 65             TextAndImageCell c = base.Clone() as TextAndImageCell;
 66             c.imageValue = this.imageValue;
 67             c.imageSize = this.imageSize;
 68             return c;
 69         }
 70 
 71         public Image Image
 72         {
 73             get
 74             {
 75                 if (this.OwningColumn == null ||
 76            this.OwningTextAndImageColumn == null)
 77                 {
 78 
 79                     return imageValue;
 80                 }
 81                 else if (this.imageValue != null)
 82                 {
 83                     return this.imageValue;
 84                 }
 85                 else
 86                 {
 87                     return this.OwningTextAndImageColumn.Image;
 88                 }
 89             }
 90             set
 91             {
 92                 if (this.imageValue != value)
 93                 {
 94                     this.imageValue = value;
 95                     this.imageSize = value.Size;
 96 
 97                     Padding inheritedPadding = this.InheritedStyle.Padding;
 98                     this.Style.Padding = new Padding(imageSize.Width,
 99                    inheritedPadding.Top, inheritedPadding.Right,
100                    inheritedPadding.Bottom);
101                 }
102             }
103         }
104         protected override void Paint(Graphics graphics, Rectangle clipBounds,
105        Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState,
106        object value, object formattedValue, string errorText,
107        DataGridViewCellStyle cellStyle,
108        DataGridViewAdvancedBorderStyle advancedBorderStyle,
109        DataGridViewPaintParts paintParts)
110         {
111             // Paint the base content
112             base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState,
113               value, formattedValue, errorText, cellStyle,
114               advancedBorderStyle, paintParts);
115 
116             if (this.Image != null)
117             {
118                 // Draw the image clipped to the cell.
119                 System.Drawing.Drawing2D.GraphicsContainer container =
120                graphics.BeginContainer();
121 
122                 graphics.SetClip(cellBounds);
123                 graphics.DrawImageUnscaled(this.Image, cellBounds.Location);
124 
125                 graphics.EndContainer(container);
126             }
127         }
128 
129         private TextAndImageColumn OwningTextAndImageColumn
130         {
131             get { return this.OwningColumn as TextAndImageColumn; }
132         }
133     }
134 }

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

  1 using System;
  2 using System.Collections.Generic;
  3 using System.ComponentModel;
  4 using System.Data;
  5 using System.Drawing;
  6 using System.Linq;
  7 using System.Text;
  8 using System.Windows.Forms;
  9 using System.Data.SqlClient;
 10 
 11 namespace DataGridViewTest
 12 {
 13     public partial class Form1 : Form
 14     {
 15         private static string imagePath = AppDomain.CurrentDomain.BaseDirectory.Substring(0, AppDomain.CurrentDomain.BaseDirectory.IndexOf("bin")) + "Images\\";//列表图片路径
 16         public Form1()
 17         {
 18             InitializeComponent();
 19             InitControlsProperties();
 20         }
 21 
 22         private void InitControlsProperties()
 23         {
 24             this.dataGridView1.AutoGenerateColumns = false;
 25             TextAndImageColumn ColumnRoleID = new TextAndImageColumn();
 26             ColumnRoleID.DataPropertyName = "RoleID";
 27             ColumnRoleID.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
 28             ColumnRoleID.Name = "RoleID";
 29             ColumnRoleID.HeaderText = "权限ID";
 30             ColumnRoleID.Width = 200;
 31             this.dataGridView1.Columns.Add(ColumnRoleID);
 32 
 33             this.dataGridView1.AutoGenerateColumns = false;
 34             TextAndImageColumn ColumnRoleName = new TextAndImageColumn();
 35             ColumnRoleName.DataPropertyName = "RoleName";
 36             ColumnRoleName.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
 37             ColumnRoleName.Name = "RoleName";
 38             ColumnRoleName.HeaderText = "权限名称";
 39             ColumnRoleName.Width = 100;
 40             this.dataGridView1.Columns.Add(ColumnRoleName);
 41 
 42             this.dataGridView1.AutoGenerateColumns = false;
 43             TextAndImageColumn ColumnDescription = new TextAndImageColumn();
 44             ColumnDescription.DataPropertyName = "Description";
 45             ColumnDescription.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
 46             ColumnDescription.Name = "Description";
 47             ColumnDescription.HeaderText = "描述";
 48             ColumnDescription.Width = 150;
 49             this.dataGridView1.Columns.Add(ColumnDescription);
 50         }
 51 
 52         private void Form1_Load(object sender, EventArgs e)
 53         {
 54             string strConn = "Data Source=XIAN-PC;Initial Catalog=ReportServer;Persist Security Info=True;User ID=sa;Password=sa";
 55             SqlConnection conn = new SqlConnection(strConn);
 56             string strSql = "select * from Roles";
 57             SqlCommand cmd = new SqlCommand(strSql, conn);
 58             SqlDataAdapter adapter = new SqlDataAdapter(cmd);
 59             DataSet ds = new DataSet();
 60             conn.Open();
 61             adapter.Fill(ds, "Roles");
 62             conn.Close();
 63             this.dataGridView1.DataSource = ds.Tables["Roles"];
 64         }
 65 
 66         private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
 67         {
 68             #region 第二列
 69             if (e.ColumnIndex == 1)
 70             {
 71                 TextAndImageCell cell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex] as TextAndImageCell;
 72                 if (cell != null && e.Value != null)
 73                 {
 74                     try
 75                     {
 76                         string ajzt = cell.Value.ToString();
 77                         string path = imagePath;
 78                         switch (ajzt)
 79                         {
 80                             case "发布者":
 81                                 path += "1.png";
 82                                 break;
 83                             case "浏览者":
 84                                 path += "2.png";
 85                                 break;                            
 86                             default:
 87                                 path += "3.png";
 88                                 break;
 89                         }
 90                         cell.Image = GetImage(path);
 91                     }
 92                     catch (Exception ex)
 93                     {
 94 
 95                     }
 96                 }
 97             }
 98             #endregion
 99         }
100 
101         public System.Drawing.Image GetImage(string path)
102         {
103             return System.Drawing.Image.FromFile(path);
104         }
105 
106     }
107 }

 

posted @ 2015-12-06 19:36  Materben  阅读(13678)  评论(1编辑  收藏  举报