【问题标题】:Center Align Cell Text in Vb.Net DataGridView在 Vb.Net DataGridView 中居中对齐单元格文本
【发布时间】:2016-08-09 13:11:45
【问题描述】:

我正在使用 DataGridView,有一种情况是我必须在选定的列中显示居中对齐文本,我已设法设置标题居中对齐文本,但使用行单元格和条件,我无法弄清楚如何?

假设我有 4 行和 3 列,ID ,Name,Type,在Type 列的基础上,我想显示我的数据,如下图所示,

在 CellFormattingEvent 中,我设法设置了不同的配色方案。

Private Sub grdDetailsNew_CellFormatting(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles grdFruitDetailsNew.CellFormatting
    Try
        If e.RowIndex > -1 Then
            If grdDetailsNew.Rows.Count > 0 Then
                If grdDetailsNew.Rows(e.RowIndex).Cells("Type").Value = 1 Then
                    e.CellStyle.BackColor = Color.FromArgb(253, 192, 97)
                    e.CellStyle.Font = New Font(e.CellStyle.Font.FontFamily, 17, FontStyle.Regular)
                ElseIf grdDetailsNew.Rows(e.RowIndex).Cells("Type").Value = 2 Then
                    e.CellStyle.BackColor = Color.FromArgb(255, 249, 237)
                    e.CellStyle.Font = New Font(e.CellStyle.Font.FontFamily, 16, FontStyle.Regular)
                Else
                    e.CellStyle.BackColor = Color.FromArgb(255, 255, 255)
                    e.CellStyle.Font = New Font(e.CellStyle.Font.FontFamily, 15, FontStyle.Regular)
                End If
            End If
        End If

    Catch ex As Exception
        WriteToLog(ex)
    End Try
End Sub
Private Sub grdDetailsNew_CellPainting(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellPaintingEventArgs) Handles grdFruitDetailsNew.CellPainting
    Try

        If e.RowIndex > -1 AndAlso e.ColumnIndex > -1 Then
            If e.ColumnIndex = 2 AndAlso grdDetailsNew.Rows(e.RowIndex).Cells("Type").Value = 1 Then
                e.CellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
            End If
        End If

    Catch ex As Exception

    End Try
End Sub

【问题讨论】:

    标签: vb.net winforms datagridview formatting


    【解决方案1】:

    只需在单元格格式化事件中添加e.CellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter。并将其从绘制事件中移除。

    例如:

    Private Sub DataGridView1_CellFormatting(sender As Object, e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
        Dim type = CInt(CType(sender, DataGridView).Rows(e.RowIndex).Cells("type").Value)
        If type = 1 andalso e.ColumnIndex = 1 Then e.CellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
    End Sub
    

    【讨论】:

    • 不,不是整行,而是特定条件下的特定列
    • 我添加了一个示例,它查找行类型字段并在两者 = 1 时重新格式化第一列
    • 实际上,您的绘图事件中似乎有正确的代码。尝试将其移动到单元格格式处理程序中。
    • 很好,它起作用了,只是将文本的 alignmnet 行移动到格式化事件中。
    猜你喜欢
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    • 2020-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-04
    相关资源
    最近更新 更多