Visual Studio中如何自定义DataGridView单元格?含单元格高度调整问询
一、自定义DataGridView单元格
自定义单元格其实就是扩展DataGridView的单元格类,根据你的需求重写绘制或编辑逻辑,我给你梳理最常用的实现步骤:
1. 创建自定义单元格类
通常我们会继承DataGridViewTextBoxCell(如果是文本类单元格)或者直接继承DataGridViewCell,核心是重写Paint方法来实现自定义外观。比如下面这个例子,实现一个值大于100时背景高亮的单元格:public class CustomHighlightCell : DataGridViewTextBoxCell { 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) { // 自定义背景色逻辑 if (value != null && int.TryParse(value.ToString(), out int cellValue) && cellValue > 100) { cellStyle.BackColor = Color.LightGreen; } else { // 恢复默认背景色 cellStyle.BackColor = this.OwningColumn.DefaultCellStyle.BackColor; } // 调用基类方法完成基础绘制 base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts); } }2. 创建对应列类(推荐)
为了方便在设计器或代码中快速使用,最好创建一个配套的列类,指定单元格模板:public class CustomHighlightColumn : DataGridViewColumn { public CustomHighlightColumn() { CellTemplate = new CustomHighlightCell(); } }3. 在DataGridView中使用
有两种方式:- 代码方式:直接添加到列集合
dataGridView1.Columns.Add(new CustomHighlightColumn() { HeaderText = "数值列", Name = "NumColumn" }); - 设计器方式:先编译项目,然后右键DataGridView→「编辑列」→「添加」→选择你创建的
CustomHighlightColumn即可。
- 代码方式:直接添加到列集合
二、调整DataGridView单元格高度(行高)
DataGridView的单元格高度由所在行的高度决定,所以调整行高就能实现需求,这里有几种常用方法:
1. 设置全局默认行高
一次性给所有行设置固定高度,或者通过内边距增加单元格内部空间:// 直接设置默认行高为40像素 dataGridView1.RowTemplate.Height = 40; // 或者增加上下内边距,让单元格内容更宽松(行高会自动适配内边距) dataGridView1.DefaultCellStyle.Padding = new Padding(2, 10, 2, 10); // 上下各10px内边距2. 自动适配内容高度
如果希望行高根据单元格内容自动调整,开启自动行高模式:// 所有行根据内容自动调整 dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells; // 只调整当前显示的行,提升性能 dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCells;3. 手动调整指定行高度
单独修改某一行的高度:// 把第0行的高度设为50像素 dataGridView1.Rows[0].Height = 50;注意事项
如果开启了自动行高模式,手动设置的行高会被覆盖,所以需要固定行高时记得关闭自动模式:dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
内容的提问来源于stack exchange,提问作者Dev
相关产品推荐
相关产品推荐

