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 }
时间: 12-04

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

ios开发 在cell中动态添加图片解决重复出现图层问题

1.在cell初始化的时候创建scrollView,然后往scrollView中添加imageView,最后在重用cell的时候动态计算scrollView的高度 总而言之,就是初始化创建控件要放在cell的init里面,赋值放init外面,不然每次循环都会重复创建imageView视图 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ UI

对dataGridView指定列相同单元格合并

//写在dataGridView1控件的CellPainting事件中 if (e.ColumnIndex==0 && e.RowIndex!=-1 || e.ColumnIndex==1 && e.RowIndex!=-1)//对第1列和第2列相同单元格进行合并 { Brush datagridBrush=new SolidBrush(dataGridView1.GridColor); SolidBrush grouplinebBrush =new SolidBrush(

WPF DataGrid动态生成列的单元格背景色绑定

原文:WPF DataGrid动态生成列的单元格背景色绑定 <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Column.DisplayIndex}" Value="1"> <Setter Property="Background" Value="{Binding RelativeSource={RelativeSour

[Winform]DataGridView列自适应宽度

引言 在做winform项目中,数据控件DataGridView的使用多多少少是会用到的,如果不设置它的属性,默认情况下是不会自适应宽度的,你想查看某项的数据,就不得不将标题栏拖来拖去,挺烦的. 方法 建一个用于测试的Person类 1 public class Person 2 { 3 [Description("姓名")] 4 public string Name { get; set; } 5 [Description("性别")] 6 public stri

jquery实现的统计table表格指定列的单元格值的和

jquery实现的统计t]able表格指定列的单元格值的和:在一些应用中,表格单元格中存放的都是数字,比如学生的分数,那么就有可能将这些分数做加法运算来统计出总分数,下面就通过代码实例介绍一下如何统计某一列单元格中值的和.代码实例: <!DOCTYPE html><html> <head> <meta charset=" utf-8"> <meta name="author" content="http

设置DataGridView的某个单元格为ComboBox

怎么将DataGridView的 某个单元格设为ComboBox的样式而不是整列都改变样式? 1.最简单的方法:利用DataGridView提供的DataGridViewComboBoxCell. 写个简单例子: 1 DataGridViewComboBoxCell cbCell = new DataGridViewComboBoxCell(); 2 string[] jgStr = new string[] {"砖混", "框混", "全框架"

Oracle BIEE某列指定单元格进行合并展示

Oracle BIEE某列指定单元格进行合并展示的最终效果,见下图: 具体操作为: 1. 将该列 列属性-列格式-值校正 设置为禁用,此时BIEE会默认将该列中相邻行且值一样的单元格进行合并显示: 2. 增加隐藏排序列(设置 列属性-列格式 为隐藏,同时点亮该列排序标识),目的是使得需要合并的记录在相邻行: 此时,BIEE会将排序列值相同的行中,对目标列中相应行进行合并单元格显示. 注意:BIEE默认从左至右依次对合并的行记录渐渐进行分割,因此需要保证行中值不同的列出现在需要合并单元格的列的右侧

GRIDVIEW多行多列合并单元格(合并列)

GitHub项目地址:https://github.com/mingceng/merge-gridviewcell 两篇文章:  GridView多行多列合并单元格(完整代码和例子)和 GridView多行多列合并单元格(指定列合并).今天继续再添加一些功能,首先看下图: 左边是原始数据的显示,右边是应用合并列之后的效果. 从图中可以看到,二级指标有两列,有的行中两列的内容一样,有的则不一样,如果实现如右图所示,看起来效果会更好一些.下面就着手实现这个功能,我的实现原理很简单,就是遍历GridV

Swift - 异步加载各网站的favicon图标,并在单元格中显示

下面是一个简单的应用,表格视图的各个单元格自动异步加载各个网站的favicon图标,并显示出来. 主要是复习下如何自定义单元格,单元格中图片的异步加载,以及didSet的用法. 效果图如下: 操作步骤: (1)先创建单元格类 - FaviconTableViewCell.swift 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39