根据外部参数更改datagridview单元格背景

时间:2014-07-18 12:53:32

标签: vb.net gridview datagridview cell

我应该将颜色更改为包含参数' tarjeta_fam'的单元格。我试图更改单元格默认属性,然后使行无效以刷新它,但(显然)没有任何反应。是否可以从单元格格式化事件中更改单元格颜色?

Public Sub New(user As Usuario, ByVal tarjeta_fam As String)
  InitializeComponent()

  gridFamiliares.DataSource = BD.getTable(a query)

  If Me.gridFamiliares.Rows.Count > 0 Then
    For i As Integer = 0 To Me.gridFamiliares.Rows.Count - 1
      If Me.gridFamiliares.Rows(i).Cells("tarjeta_fam").Value = tarjeta_fam Then
         Me.gridFamiliares.Rows(i).DefaultCellStyle.BackColor = Color.Black
         Me.gridFamiliares.InvalidateRow(i)
      End If
    Next
    End If
End Sub

1 个答案:

答案 0 :(得分:1)

DataGridView控件确实希望您为此使用CellFormatting事件,因此声明该事件使用的表单级变量:

Private tarjeta_fam_Value As String = String.Empty

Public Sub New(user As Usuario, ByVal tarjeta_fam As String)
  InitializeComponent()
  gridFamiliares.DataSource = BD.getTable(a query)
  tarjeta_fam_Value = tarjeta_fam
End Sub

Private Sub gridFamiliares_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles gridFamiliares.CellFormatting
  If tarjeta_fam_Value <> String.Empty Then
    With gridFamiliares.Rows(e.RowIndex)
      If .Cells("tarjeta_fam").Value = tarjeta_fam_Value Then
        .DefaultCellStyle.BackColor = Color.Black
      End If
    End With
  End If
End Sub