中心在Vb.Net DataGridView中对齐单元格文本

时间:2016-08-09 04:58:52

标签: vb.net winforms datagridview formatting

我正在使用DataGridView,并且有一个场景我必须在所选列中显示居中的对齐文本,我已设法设置Header Center Align Text但是使用Row Cell和Conditions,我无法弄清楚如何?< / p>

假设我有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

1 个答案:

答案 0 :(得分: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