2016-08-09 96 views
0

我正在使用DataGridView,並且有一個場景,我必須顯示居中對齊選定列中的文本,我設法設置標題中心對齊文本但行單元格和條件,我無法弄清楚如何?中心對齊Vb.Net中的單元格文本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 

回答

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 
+0

不,不是滿列但我添加看起來針對行類型字段並重新格式化所述第一列中的例如在某些條件 – DareDevil

+0

某一列如果兩個= 1 – FloatingKiwi

+1

實際上它看起來你在繪畫事件中有正確的代碼。嘗試將它移入單元格格式化處理程序中。 – FloatingKiwi

相關問題