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

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. 201621123023《Java程序设计》第3周学习总结

    一. 本周学习总结 写出你认为本周学习中比较重要的知识点关键词,如类.对象.封装等 关键字:面向对象,类,对象,构造函数,封装,继承 用思维导图或者Onenote或其他工具将这些关键词组织起来 二.书 ...

  2. Ubuntu16.04中把默认JAVA设置为Oracle的JDK!

    系统当中已经存在了OpenJDK,默认的JDK是它,并不是Oracle的JDK,执行下面操作就可以把Oracle的JDK设置为默认的了! 首先假设我们已经把Oracle的JDK安装和配置好了,但是就是 ...

  3. [SinGuLaRiTy] 关于博客

    由于博主主要使用Chrome内核的浏览器进行博客页面的代码优化,因此有些功能可能会因为浏览器的差异而无法正常运行,博主对此也非常无奈啊:Windows的IE浏览器的兼容性实在是太差了...... 尽管 ...

  4. java 程序设计第一次作业

    public class Join{ public static void main(String args[]){ String s1=new String("hello"); ...

  5. EXPORT Man Information for Linux use COMMAND col

    col命令 是一个标准输入文本过滤器,它从标注输入设备读取文本内容,并把内容显示到标注输出设备.在许多UNIX说明文件里,都有RLF控制字符.当我们运用shell特殊字符>和>>,把 ...

  6. Linux-Web应用服务性能测试初探

    一.服务端与客户端的准备工作 对于服务器最想要的数据就是,每秒支持的并发数,以及相应的内存CPU使用情况. 服务端需要设置最大打开描述符的限制(以支持创建大量的socket),配置socket参数.客 ...

  7. ElasticSearch 从2.2升级到6.2.4所碰到的问题汇总

    1.ID的问题. 以前创建索引API直接用URL加索引Post过去就行了,或者在Kibana的开发工具中提交命令 PUT /customer?pretty 但是发现这样即使生成了索引,在ES中预览能看 ...

  8. centos7 装机配置及 mysql 安装过程

    打开网卡,使操作系统可以上网 1 ip add 查看网卡,lo是回环网卡可以忽略,ens33为实际网卡. [root@localhost ~]# ip add 1: lo: <LOOPBACK, ...

  9. 每一次要fix的pr

    1.TODO一定要加自己名字 2.写代码考虑别人的阅读,比如event这样很general的名字不要用,所以不用from sqlalchemy import event, 要用import sqlal ...

  10. btn按钮事件

    1.用Delegate 和 Event 来定义一个通用类来处理事件 (观察者模式) using System.Collections; using System.Collections.Generic ...