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

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. 怎样把网站js文件合并成一个?几种方法可以实现

    我们在建网站时经常会用js特效代码以使页面更美观,比如js幻灯片代码.js下拉菜单等,但是网页特效一多,如果js文件没有合并的话会降低网站的性能,这时我们就要考虑合并js文件了,ytkah总结了以下几 ...

  2. Android java.lang.UnsupportedClassVersionError: com/android/dx/command/Main : Unsupported major.minor ver

    java.lang.UnsupportedClassVersionError: com/android/dx/command/Main : Unsupported major.minor ver 解决 ...

  3. mysql 的卸载、再安装与常用命令

    1.卸载mysql.完全删除: 删除 mysqlsudo apt-get autoremove --purge mysql-server-5.0sudo apt-get remove mysql-se ...

  4. Java中Iterator(迭代器)的用法及其背后机制的探究

    在Java中遍历List时会用到Java提供的Iterator,Iterator十分好用,原因是: 迭代器是一种设计模式,它是一个对象,它可以遍历并选择序列中的对象,而开发人员不需要了解该序列的底层结 ...

  5. 使用java的Calendar工具类获取到本月的第一天起始时间和最后一天结束时间。

    1.使用java的Calendar工具类获取到本月的第一天起始时间和最后一天结束时间. package com.fline.aic.utils; import java.text.DateFormat ...

  6. [cloud][sdn] openstack openflow opendaylight openvswitch

    https://www.quora.com/What-is-the-relation-between-OpenStack-OpenDaylight-OpenFlow-and-Open-vSwitch- ...

  7. 【代码笔记】iOS-长条label

    一,效果图. 二,代码. ViewController.m - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup ...

  8. RecyclerView源码分析(一)--整体设计

    RecyclerView这个控件出来已经有一段时间了,如果看这篇文章的你,还没有使用过这个控件.那请先去学习怎样使用.不然看也白看.这里奉上一些关于介绍RecyclerView使用方法的优秀博客: 鸿 ...

  9. DP专题&#183;二

    1.hdu 1260 Tickets 题意:有k个人,售票员可以选择一个人卖,或者同时卖给相邻的两个人.问最少的售票时间. 思路:dp[i] = min(dp[i - 1] + singlep[i], ...

  10. IntelliJ IDEA 快速搭建 Spring MVC环境

    IntelliJ在业界被公认为最好的java开发工具之一,尤其在智能代码助手.代码自动提示.重构.J2EE支持.Ant.JUnit.CVS整合.代码审查. 创新的GUI设计等方面的功能可以说是超常的. ...