Winform中DataGridView按钮列如何实现按钮文本多行显示
你设置的Environment.NewLine没有生效,是因为DataGridViewButtonColumn默认的绘制逻辑没有开启文本换行渲染,会直接忽略换行符按单行绘制。你可以通过自定义单元格绘制的方式实现多行按钮文本,具体实现如下:
实现步骤
- 保留你原本创建按钮列的代码,额外将DataGridView的行高调整到足以容纳多行文本的高度,保证多行文本可以完全显示。
- 为DataGridView绑定
CellPainting事件,自定义按钮文本的绘制逻辑,支持识别换行符实现多行渲染。
VB.NET 实现代码
按钮列创建代码(原有代码无需大幅修改,仅需补充行高设置和事件绑定):
' 原有按钮列创建逻辑 Dim inspectionNotesButtonCol As New DataGridViewButtonColumn With { .Name = "InspNotesButton", .HeaderText = "Insp." + Environment.NewLine + "Notes", .Text = "Insp." + Environment.NewLine + "Notes", .UseColumnTextForButtonValue = True, .Width = 50 } Me.dgvIssues.Columns.Add(inspectionNotesButtonCol) ' 额外设置行高适配两行文本 Me.dgvIssues.RowTemplate.Height = 40 ' 绑定单元格绘制事件 AddHandler dgvIssues.CellPainting, AddressOf dgvIssues_CellPainting
事件处理方法:
Private Sub dgvIssues_CellPainting(sender As Object, e As DataGridViewCellPaintingEventArgs) ' 仅处理目标按钮列的非表头单元格 If e.ColumnIndex = dgvIssues.Columns("InspNotesButton").Index AndAlso e.RowIndex >= 0 Then e.Paint(e.CellBounds, DataGridViewPaintParts.All And Not DataGridViewPaintParts.ContentForeground) ' 配置文本居中、换行渲染规则 Dim format As New StringFormat() With { .Alignment = StringAlignment.Center, .LineAlignment = StringAlignment.Center, .FormatFlags = StringFormatFlags.NoClip } ' 绘制带换行的按钮文本 e.Graphics.DrawString(e.FormattedValue.ToString(), e.CellStyle.Font, Brushes.Black, e.CellBounds, format) e.Handled = True End If End Sub
C# 实现代码
按钮列创建:
DataGridViewButtonColumn inspectionNotesButtonCol = new DataGridViewButtonColumn { Name = "InspNotesButton", HeaderText = "Insp.\r\nNotes", Text = "Insp.\r\nNotes", UseColumnTextForButtonValue = true, Width = 50 }; dgvIssues.Columns.Add(inspectionNotesButtonCol); // 设置行高适配多行文本 dgvIssues.RowTemplate.Height = 40; // 绑定单元格绘制事件 dgvIssues.CellPainting += dgvIssues_CellPainting;
事件处理方法:
private void dgvIssues_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { if (e.ColumnIndex == dgvIssues.Columns["InspNotesButton"].Index && e.RowIndex >= 0) { e.Paint(e.CellBounds, DataGridViewPaintParts.All & ~DataGridViewPaintParts.ContentForeground); StringFormat format = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center, FormatFlags = StringFormatFlags.NoClip }; e.Graphics.DrawString(e.FormattedValue.ToString(), e.CellStyle.Font, Brushes.Black, e.CellBounds, format); e.Handled = true; } }
效果说明
上述方案会保留系统默认的按钮外观样式,仅替换文本绘制逻辑,自动识别预设的换行符实现多行居中显示,不需要修改其他默认配置。
内容的提问来源于stack exchange,提问作者E. A. Bagby
相关产品推荐
相关产品推荐

