DataGridView 初始化完成后,在combox里显示颜色,如这样:

DataGridView 注册 cellPainting事件:
private void m_dataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
var a = e.Value; if (a != null && LstColors.Contains(a))
{
var color = GetColorFromCode(a.ToString()); var g = e.Graphics;
Brush b=new SolidBrush(color);
var rec = e.CellBounds; rec.X += 2;
rec.Y += 2;
rec.Width -= 20;
rec.Height -= 10; e.PaintContent(rec);
g.FillRectangle(b, rec);
e.Handled = true;
} }
public partial class Form1 : Form
{ private string xml =
@"<?xml version='1.0' standalone='yes'?>
<GenioCodes>
<Code No.='1' name='A' Colour='Blue' />
<Code No.='2' name='B' Colour='Green' />
<Code No.='3' name='C' Colour='Red' />
<Code No.='4' name='N' Colour='Black' />
</GenioCodes>"; DataSet m_dataSet = new DataSet();
List<ComboBox>ListCbx=new List<ComboBox>();
public Form1()
{
InitializeComponent(); // reading xml from string
var reader = XmlReader.Create(new StringReader(xml));
m_dataSet.ReadXml(reader);
m_dataGridView.DataSource = m_dataSet.Tables[0]; var column = m_dataGridView.Columns["Colour"];
int idx = column.Index;
// removing text column
m_dataGridView.Columns.RemoveAt(idx); // adding comboBox column
var cbo = new DataGridViewComboBoxColumn
{
Name = "color",
DataPropertyName = "Colour",
};
// unique color codes for comboBox
var colorCodes = m_dataSet.Tables[0].AsEnumerable()
.Select(r => r["Colour"])
.Distinct()
.ToList();
cbo.DataSource = colorCodes; // restore column in orignal position
m_dataGridView.Columns.Insert(idx, cbo);
m_dataGridView.EditingControlShowing += ComboBoxShowing; //disallow adding and deleting rows
m_dataGridView.AllowUserToAddRows = false;
m_dataGridView.AllowUserToDeleteRows = false; } /// <summary>
/// Activates custom drawing in comboBoxes
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ComboBoxShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control is ComboBox theCB)
{
theCB.DrawMode = DrawMode.OwnerDrawFixed;
try
{
theCB.DrawItem -= new DrawItemEventHandler(this.ComboItemDraw); }
catch { }
theCB.DrawItem += new DrawItemEventHandler(this.ComboItemDraw); ListCbx.Add(theCB);
}
} /// <summary>
/// Custom drawing for comboBox items
/// </summary>
private void ComboItemDraw(object sender, DrawItemEventArgs e)
{
Graphics g = e.Graphics; Rectangle rDraw = e.Bounds;
rDraw.Inflate(-1, -1); bool bSelected = Convert.ToBoolean(e.State & DrawItemState.Selected);
bool bValue = Convert.ToBoolean(e.State & DrawItemState.ComboBoxEdit); rDraw = e.Bounds;
rDraw.Inflate(-1, -1); if (bSelected & !bValue)
{
g.FillRectangle(Brushes.LightBlue, rDraw);
g.DrawRectangle(Pens.Blue, rDraw);
}
else
{
g.FillRectangle(Brushes.White, e.Bounds);
} if (e.Index < 0)
return;
string code = ((ComboBox)sender).Items[e.Index].ToString(); Color c = GetColorFromCode(code);
string s = c.ToString(); SolidBrush b = new SolidBrush(c);
Rectangle r = new Rectangle(e.Bounds.Left, e.Bounds.Top, e.Bounds.Width, e.Bounds.Height);
g.FillRectangle(b, r);
g.DrawRectangle(Pens.Black, r);
//g.DrawString(s, Form.DefaultFont, Brushes.Black, e.Bounds.Left + 25, e.Bounds.Top + 1); b.Dispose(); }
List<String> LstColors = new List<string>() { "Blue", "Green", "Red", "Black" };
/// <summary>
/// Returns color for a given code
/// </summary>
/// <param name="code"></param>
/// <returns></returns>
private Color GetColorFromCode(string code)
{
switch (code)
{
case "Blue": return Color.Blue;
case "Green": return Color.Green;
case "Red": return Color.Red;
case "Black": return Color.Black;
}
return Color.Red;
}
int index; private void m_dataGridView_CellEnter(object sender, DataGridViewCellEventArgs e)
{
index = e.RowIndex;
//实现单击一次显示下拉列表框
if (m_dataGridView.Columns[e.ColumnIndex] is DataGridViewComboBoxColumn && e.RowIndex != -1)
{
SendKeys.Send("{F4}");
}
} private void m_dataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
var a = e.Value; if (a != null && LstColors.Contains(a))
{
var color = GetColorFromCode(a.ToString()); var g = e.Graphics;
Brush b=new SolidBrush(color);
var rec = e.CellBounds; rec.X += 2;
rec.Y += 2;
rec.Width -= 20;
rec.Height -= 10; e.PaintContent(rec);
g.FillRectangle(b, rec);
e.Handled = true;
} }
}

来自问题:https://q.cnblogs.com/q/137678/#a_279065

C# Datagridview combox列 初始化颜色的更多相关文章

  1. .NET组件控件实例编程系列——5.DataGridView数值列和日期列

    在使用DataGridView编辑数据的时候,编辑的单元格一般会显示为文本框,逻辑值和图片会自动显示对应类型的列.当然我们自己可以手工选择列的类型,例如ComboBox列.Button列.Link列. ...

  2. DataGridView数值列和日期列

    本文转自:http://www.cnblogs.com/conexpress/p/5923324.html 在使用DataGridView编辑数据的时候,编辑的单元格一般会显示为文本框,逻辑值和图片会 ...

  3. ALV的颜色分为行的颜色、列的颜色和CELL的颜色

    ALV的颜色分为行的颜色.列的颜色和CELL的颜色.任务要求,将一定的Tabellenfeld 用黄色填充,也就是说CELL的颜色 DATA:ls_cellcolorTYPElvc_s_scol,co ...

  4. DataGridView绑定数据库,取得的数据插入到DataGridView指定列(一)

    实现: 点击button1,从数据库中获得数据,指定数据库的某列数据插入到DataGridView指定列 一.双击button1进入事件代码 private void button1_Click(ob ...

  5. HTML输出 一 控制列背景颜色

    #将需要读取的域名和端口列表保存在名为ports01.txt.ports02的文件中,文件与脚本位于相同目录下$CurrentPath = $MyInvocation.MyCommand.Path.s ...

  6. groupbox 下的datagridview的列标题字体修改混乱

        groupbox 下的datagridview的列标题字体修改混乱

  7. dev gridControl 自定义绘制列头颜色

    1.添加事件CustomDrawColumnHeader private void gvw1_CustomDrawColumnHeader(object sender, DevExpress.Xtra ...

  8. C#中关于DataGridView行和列的背景色-前景色设置

    关于DataGridView行和列的背景色-前景色设置 1.设定DataGridView全部单元格的Style  DataGridView内所有单元格的Style变更,可以使用DataGridView ...

  9. datagridview 日期列排序

    1.datagridview 日期列排序 private void Form1_Load(object sender, EventArgs e) { //方法1 dataGridView1.Colum ...

  10. (转)datagridview 自定义列三步走

    本文转载自:http://blog.csdn.net/zx13525079024/article/details/4814642 我们如果想自定义实现datagridview的某列,例如是datagr ...

随机推荐

  1. Git 12 IDEA上传本地项目到远程

    这里以上传 Spring 开源项目到 Gitee 为例: 1.点击 Create Git Repository 2.选择项目目录 3.添加到缓存库 4.提交到本地库 5.复制远程库地址 6.推送到远程 ...

  2. 掌握 xUnit 单元测试中的 Mock 与 Stub 实战

    引言 上一章节介绍了 TDD 的三大法则,今天我们讲一下在单元测试中模拟对象的使用. Fake Fake - Fake 是一个通用术语,可用于描述 stub或 mock 对象. 它是 stub 还是 ...

  3. HarmonyOS远端状态订阅开发实例

     IPC/RPC提供对远端Stub对象状态的订阅机制, 在远端Stub对象消亡时,可触发消亡通知告诉本地Proxy对象.这种状态通知订阅需要调用特定接口完成,当不再需要订阅时也需要调用特定接口取消.使 ...

  4. VulnHub-Jangow-01-1.0.1打靶记录

    知识点 NMAP参数 -sV 获取系统信息 -sT TCP扫描可能会留下日志记录 -sC 使用默认脚本(在-A模式下不需要) -p1-xxx 扫描端口号 -p- ==>等价于 -p1-65535 ...

  5. kubelet 原理分析

    Reference https://atbug.com/kubelet-source-code-analysis/ kubelet 简介 kubernetes 分为控制面和数据面,kubelet 就是 ...

  6. 【Oracle】力扣简单的练习题

    Oracle力扣简单的练习题 请你编写一个 SQL 查询来交换所有的 'f' 和 'm' /* Write your PL/SQL query statement below */ /******** ...

  7. 基于阿里云 ASK 的 Istio 微服务应用部署初探

    简介: 本文会通过在 ASK 上试用 Istio 部署微服务应用的方式,来验证 ASK 对标准 Kubernetes 的兼容性.Istio 作为 Service Mesh(服务网格)的领导解决方案,一 ...

  8. Flink SQL 性能优化:multiple input 详解

    简介: 在 Flink 1.12 中,针对目前 operator chaining 无法覆盖的场景,推出了 multiple input operator 与 source chaining 优化.该 ...

  9. [MySQL] 原生全文检索 fulltext 的简单应用

    在目标字段上添加全文检索:alter table 表名 add fulltext(字段) with parser ngram 查询语句:select * from xxx where match(字段 ...

  10. [Gin] gin-jwt 中间件的请求流程与使用思路

    gin-jwt 中间件是对 jwt-go 的封装以适应 gin 框架.gin-jwt 对不同的请求流程有不同的 handler: 登录请求流程 是用 LoginHandler. 需要 jwt 令牌的后 ...