DataGridView 自绘Row的背景
DataGridView 可以指定row的BackColor, 这个在许多文章中都有, 但是如何自绘Row的背景,这个却不多见。
例如一行背景颜色需要能左侧,中间,右侧的背景各不相同。
实现如下:
1. 要求默认的Cell的背景颜色为Transparent, 否则绘画是无效的
base.CellFormatting += base_CellFormatting;
base.RowPrePaint += base_RowPrePaint;
private void base_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
var row = base.Rows[e.RowIndex];
row.DefaultCellStyle.BackColor = Color.Transparent;
}
2.在绘画Row的函数中绘画背景
private void base_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
int x = e.RowBounds.Left;
int y = e.RowBounds.Top;
int width = base.Columns.GetColumnsWidth(DataGridViewElementStates.Displayed);
int height = e.RowBounds.Height;
using(SolidBrush bru = new SolidBrush(Color.Blue)
{
e.Graphics.FillRectangle(bru, x, y, width, height);
}
}
3.在实际使用中,我们往往会用到下面几个工具函数:
DataGridView.Columns.GetColumnsWidth(DataGridViewElementStates.Displayed) //获取DataGridView整个显示的长度
DataGridView.Columns[$"{nameof(DataClass.Item)}"] //DataClass为绑定的数据类型
DataGridView.GetCellDisplayRectangle(columnIndex, rowIndex, false) //获取某一个Cell(或者Column)的位置
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能