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

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);
} }
}

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

  1. 周记4——vue中动态添加图片无效、build上线后background-image路径问题

    又是一个周五,又一周要过去了...很开心,这周遇到了vue中的一个比较常见的坑,网上随便一搜就有了很多解决方案...“幸运”的是,我选了一个带坑的方案...所以我觉得有必要记录一下这个“坑中坑”... ...

  2. DataGridView中实现点击单元格Cell动态添加自定义控件

    场景 鼠标点击DataGridView的某个单元格时,此单元格添加一个自定义的控件,这里以 添加下拉框为例 效果 注: 博客主页: https://blog.csdn.net/badao_liuman ...

  3. winform DataGridView双击修改单元格的值 分类: DataGridView 2014-08-04 19:39 150人阅读 评论(0) 收藏

    定义全局变量 string abcmycode = "";//当前行自编号 bool tf = false;//是否双击 //双击可编辑         private void ...

  4. WinForm中DataGridView复制选中单元格内容解决方案

    WinForm中DataGridView鼠标选中单元格内容复制方案 1.CTR+C快捷键复制 前提:该控件ClipboardCopyMode属性设置值非Disable: 2.鼠标框选,自定义代码实现复 ...

  5. easyui datagrid动态设置行、列、单元格不允许编辑

    Easyui datagrid 行编辑.列编辑.单元格编辑设置 功能: 动态对datagrid 进行行.列.单元格编辑进行设置不允许编辑. 禁用行编辑: 在编辑方法调用前,对选择的行进行判断,如果不允 ...

  6. python 将表格多个列数据放到同一个单元格中

      表格模板: 目的将卡片1到卡片5的所有数据组合起来到一个单元格中如下入F列中(工作中为了避免手动复制粘贴),其余不变,因为数据太多 自己一个一个复制工作效率太低,所以写这个脚本是为了方便自己有需要 ...

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

    <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Column.DisplayInde ...

  8. [Winform]DataGridView列自适应宽度

    引言 在做winform项目中,数据控件DataGridView的使用多多少少是会用到的,如果不设置它的属性,默认情况下是不会自适应宽度的,你想查看某项的数据,就不得不将标题栏拖来拖去,挺烦的. 方法 ...

  9. 设置DataGridView的某个单元格为ComboBox

    怎么将DataGridView的 某个单元格设为ComboBox的样式而不是整列都改变样式? 1.最简单的方法:利用DataGridView提供的DataGridViewComboBoxCell. 写 ...

随机推荐

  1. [SDOI2009] HH的项链 | 莫队模板

    题目链接:戳我 题意:求区间中不同颜色的种类数 因为是要过知识点,所以又把这题拿出来做了一遍......这里就写两种方法吧 主席树做法 设pre[i]为第i个点上的颜色在前面序列中出现的最晚的一次的位 ...

  2. Ionic2的CLI的命令行

    http://blog.csdn.net/qq_33315185/article/details/68067747 在我们开发Ionic app的时候 CLI 是一个非常重要的工具.CLI包含了很多开 ...

  3. 网络传输层之TCP/UDP详解

    一.运输层协议概述 从通信和信息处理的角度看,运输层向它上面的应用层提供通信服务,它属于面向通信部分的最高层,同时也是用户功能中的最低层. 运输层的任务就是负责主机中两个进程之间的通信,其数据传输的单 ...

  4. (USB HID) Configuration Descriptor

    最近完成了HID的基本收發,使用的配置用了2個Endpoint,把一些特別重要要的地方紀錄下來 整個Configuration 分成4大部分 : 1. Configuration 2. Interfa ...

  5. history.back返回是浏览器错误码:ERR_CACHE_MISS

    解决方法: 如果访问的是php文件中添加:header("Cache-control: private"); 如果使用的是模板引擎(tp5):{php}header("C ...

  6. 「DB」数据库事务的隔离级别

    *博客搬家:初版发布于 2017/04/10 00:37    原博客地址:https://my.oschina.net/sunqinwen/blog/875833 数据库事务的隔离级别 讲事务的隔离 ...

  7. 分分钟钟学会Python - 数据类型(list、tuple)

    第四节 数据类型(列表.元祖) 今日内容 列表 元祖 1.列表 1.格式 users = ["ji",1,3,"gyhj"] 2.公共方法 1.len #计算长 ...

  8. Oracle汉字用户名数据脱敏长度不变,rpad函数使用

    信息安全考虑,有时需要对用户名称进行数据脱敏. 针对Oracle数据库,进行取数数据脱敏处理 脱敏规则: 长度小于9个字符,只保留前3个汉字与后3个汉字,中间全部由*填充. 长度9个字及以上及奇数,隐 ...

  9. vue开发的一些设置以及技巧

    引入其它css样式   需要加~   @找到的是src目录 对于常用的路径可以设置别名     @代表src                  常用的地址在webpack.base.conf.js中 ...

  10. touch插件

    第一种: <script> (function($) { var options, Events, Touch; options = { x: 20, y: 20 }; Events = ...