2016-08-09 51 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

相关问题