DareDevil DareDevil - 1 year ago 276
Vb.net Question

Center Align Cell Text in Vb.Net DataGridView

I am working with DataGridView and there is a scenario that I have to show centered align text in selected columns, I have managed to set Header Center Align Text but with Row Cell and Conditions, I am unable to figure out how?

Suppose I have 4 Rows with 3 Columns,

ID ,Name,Type
, On the bases of
column I want to show my data as given below picture,

In CellFormattingEvent I have managed to set different color scheme.

Private Sub grdDetailsNew_CellFormatting(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles grdFruitDetailsNew.CellFormatting
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)
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
End Try
End Sub
Private Sub grdDetailsNew_CellPainting(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellPaintingEventArgs) Handles grdFruitDetailsNew.CellPainting

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

Answer Source

Just add e.CellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter inside the cell formatting event. And remove it from the paint event.


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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download