缘起

很久以前给datagridview绑定列的时候都是手动的,记得以前用Display自定义属性来动态给datagridview绑定列。后来发现不行,于是还在博问发了问题:

后来热心网友帮我回答了这个问题,一试还真可以。再次记录一下。

测试流程:

1) View Entity:

 /// <summary>
/// IPC完工成品情况查询实体
/// </summary>
public class GdvSourceProductRpt
{
[DisplayName("客户名称")]
public string custerName { get; set; }
[DisplayName("成品订单号")]
public string orderNo { get; set; } [DisplayName("产品名称")]
public string InvName { get; set; } [DisplayName("制令")]
public string mo_code { get; set; } [DisplayName("物料号")]
public string goods_code { get; set; } [DisplayName("订单量")]
public int order_count { get; set; } [DisplayName("制令数")]
public int mo_count { get; set; } [DisplayName("成品产量")]
public int scanNum { get; set; } [ProgressBarCell(Style = 1)]
[DisplayName("完成度")]
public double rate { get; set; }
}

2)DataGridView的DataSource设置为窗体里的 BindingSource,DataGridView自动完成中文列名的显示

这个是手工操作按下不表

3)实现动态绑定列,实现多个数据源在一个DataGridView里显示

 /// <summary>
/// 动态绑定DataGridView的列
/// </summary>
/// <param name="t"></param>
/// <param name="dgv"></param>
protected virtual void BingGridColumn(Type t,DataGridView dgv)
{
dgv.Columns.Clear();
var props = t.GetProperties().Where(prop => prop.GetCustomAttributes(typeof(DisplayNameAttribute), false).Any());
int col_width = dgv.Width / props.Count() - 8;
foreach (var prop in props)
{
DisplayNameAttribute attrib = (DisplayNameAttribute)prop.GetCustomAttributes(typeof(DisplayNameAttribute), false).FirstOrDefault();
if (prop.GetCustomAttributes(typeof(ProgressBarCellAttribute), false).Any())
{
DataGridViewProgressBarColumn dc = new DataGridViewProgressBarColumn();
dc.Name = "col" + prop.Name;
dc.HeaderText = attrib.DisplayName;
dc.DataPropertyName = prop.Name;
dc.Width = col_width;
dgv.Columns.Add(dc);
}
else
{
DataGridViewTextBoxColumn dc = new DataGridViewTextBoxColumn();
dc.Name = "col" + prop.Name;
dc.HeaderText = attrib.DisplayName;
dc.DataPropertyName = prop.Name;
dc.Width = col_width;
dgv.Columns.Add(dc);
}
}
}

使用:

效果:

顺便贴一下代码,如何实现DataGridView进度条列。

 public class DataGridViewProgressBarCell : DataGridViewCell
{
public DataGridViewProgressBarCell()
{
this.ValueType = typeof(decimal);
} //设置进度条的背景色;
public DataGridViewProgressBarCell(Color progressBarColor)
: base()
{
ProgressBarColor = progressBarColor;
} protected Color ProgressBarColor = Color.Green; //进度条的默认背景颜色,绿色;
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)
{
using (SolidBrush backBrush = new SolidBrush(cellStyle.BackColor))
{
graphics.FillRectangle(backBrush, cellBounds);
}
base.PaintBorder(graphics, clipBounds, cellBounds, cellStyle, advancedBorderStyle);
using (SolidBrush brush = new SolidBrush(ProgressBarColor))
{
if (value == null)
value = 0;
decimal num = System.Convert.ToDecimal(value);
float percent = (float)(num / System.Convert.ToDecimal(100));
graphics.FillRectangle(brush, cellBounds.X, cellBounds.Y + 1, cellBounds.Width * percent, cellBounds.Height - 3);
string text = string.Format("{0}%", num);
SizeF rf = graphics.MeasureString(text, cellStyle.Font);
float x = cellBounds.X + (cellBounds.Width - rf.Width) / 2f;
float y = cellBounds.Y + (cellBounds.Height - rf.Height) / 2f;
Color txtColor = Color.Lime;
if (System.Convert.ToDecimal(value) < 10)
txtColor = Color.OrangeRed;
if (System.Convert.ToDecimal(value) < 50 && System.Convert.ToDecimal(value) > 20)
txtColor = Color.DarkBlue;
graphics.DrawString(text, cellStyle.Font, new SolidBrush(txtColor), x, y);
}
}
}
 public class DataGridViewProgressBarColumn : DataGridViewColumn
{
public DataGridViewProgressBarColumn()
: base(new DataGridViewProgressBarCell())
{
CellTemplate = new DataGridViewProgressBarCell();
}
}

分享Winform datagridview 动态生成中文HeaderText的更多相关文章

  1. winform中动态生成多行label,同时添加滚动条

    设计思路大概是这样的,Form内添加一个groupBox,groupBox内添加一个panel,panel的属性AutoScroll=true,在panel内动态添加label. 原始From如下: ...

  2. [WinForm]dataGridView动态加载以本地图片显示列

    增加一个图片列: C# private void btnQuery_Click(object sender, EventArgs e) { StringBuilder sb=new StringBui ...

  3. 分享我基于NPOI+ExcelReport实现的导入与导出EXCEL类库:ExcelUtility (续3篇-导出时动态生成多Sheet EXCEL)

    ExcelUtility 类库经过我(梦在旅途)近期不断的优化与新增功能,现已基本趋向稳定,功能上也基本可以满足绝大部份的EXCEL导出需求,该类库已在我们公司大型ERP系统全面使用,效果不错,今天应 ...

  4. 动态生成二维码并利用canvas合成出一张图片(类似海报、分享页)

    在前端开发并打算推广一个APP的时候,推广页是免不了的,而推广页的展示方式一般是给人家一个二维码,让别人自己去安装APP,这样前段任务也达到了,这次写这篇文章的原因主要还是总结一下,其中有很多不完善的 ...

  5. 动态生成CheckBox(Winform程序)

    在做用户权限设置功能时,需要做一个动态生成权限列表的功能.(笔记.分享) //1.清空权限控件组的默认控件 panelPermissions.Controls.Clear(); _groupBoxLi ...

  6. winform WebBrowser控件中,cs后台代码执行动态生成的js

    很多文章都是好介绍C# 后台cs和js如何交互,cs调用js方法(js方法必须是页面上存在的,已经定义好的),js调用cs方法, 但如果想用cs里面执行动态生成的js代码,如何实现呢? 思路大致是这样 ...

  7. C#实现WinForm DataGridView控件支持叠加数据绑定

    我们都知道WinForm DataGridView控件支持数据绑定,使用方法很简单,只需将DataSource属性指定到相应的数据源即可,但需注意数据源必须支持IListSource类型,这里说的是支 ...

  8. Java 动态生成 复杂 .doc文件

    阅读目录 1.word 里面调整好排版,包括你想生成的动态部分,还有一些不用生成的规则性的文字 2. 将 word 文档保存为 xml 3.用 Firstobject free XML edito 打 ...

  9. 基于DevExpress的BandedGridView动态生成多行(复合)表头

    最近cs项目中有个看板的功能需求,整个系统是基于DevExpress组件开发的,由于对这个组件的布局不是很熟,也借鉴了网上一些其他人的做法,普遍都是通过GridControl的BandedGridVi ...

随机推荐

  1. Spring基础系列-参数校验

    原创作品,可以转载,但是请标注出处地址:https://www.cnblogs.com/V1haoge/p/9953744.html Spring中使用参数校验 概述 ​ JSR 303中提出了Bea ...

  2. Java设计模式总结

    什么是设计模式   设计模式(Design pattern)是一套被反复使用.多数人知晓的.经过分类编目的.代码设计经验的总结.通过对这些设计模式的合理使用能够是我们的系统更加的健壮. 六大设计原则 ...

  3. eclipse创建的maven项目,pom.xml文件报错解决方法

    [错误一:]maven 编译级别过低 [解决办法:] 使用 maven-compiler-plugin 将 maven 编译级别改为 jdk1.6 以上: <!-- java编译插件 --> ...

  4. 使用LR编写下载类脚本

    如何下载并保存文件到本地,实现文件下载的脚本制作.以下是本人测试某系统总结整理的脚本,仅供参考. #include "lrs.h" Action() { // 示例一: //第一种 ...

  5. .net core EFCore CodeFirst 迁移出现错误【No project was found. Change the current working directory or use the --project option. 】

    PM> dotnet ef Migrations add Init No project was found. Change the current working directory or u ...

  6. c# ?? 和?

    static void Main(string[] args)      {                  double? num1 = null; // ? 说明num1可以为空        ...

  7. aspx 页面中 js 引用与页面后台的数据交互 --【 后台调用 js 】

    js 中调用后台方法   一.用Response.Write方法 Response.Write("<script type='text/javascript'>alert(&qu ...

  8. Java开发笔记(六十八)从泛型方法探究泛型的起源

    前面介绍各种容器之时,通过在容器名称后面添加包裹数据类型的一对尖括号,表示该容器存放的是哪种类型的元素.这样一来总算把Java当中的各类括号都凑齐了,例如包裹一段代码的花括号.指定数组元素下标的方括号 ...

  9. xxxx-xx-xx的时间的加减

    <!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="UTF-8& ...

  10. C# Html格式内容转Csv内容包括table(重点在rowspan和colspan合并),p,div元素

    Html格式内容转Csv内容,包括table(重点在rowspan和colspan合并),p,div元素,table不能包含嵌套功能. /// <summary> /// Html格式内容 ...