Gridview中的ASP.NET VB Color单行

时间:2016-01-17 16:23:27

标签: asp.net vb.net gridview

我希望在Gridview中显示为空时为单行着色,但它会将每行的颜色更改为空而不是。

Private Sub _Default_Load(sender As Object, e As EventArgs) Handles Me.Load

... SQL Connection Stuff

Using dt As New DataTable()
sda.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()

Dim Menge As Integer = GridView1.Rows.Count - 1

For i = 0 To Menge
  For Each row As GridViewRow In GridView1.Rows
    If GridView1.Rows(i).Cells(4).Text = "" Then
      GridView1.Rows(i).Cells(4).BackColor = System.Drawing.Color.Red
  End If
  Next
Next

End Sub

有人能帮助我吗?

1 个答案:

答案 0 :(得分:0)

您应该在Default_Load事件中使用以下代码,但这只会在页面加载时对行进行着色。理想情况下,您应该使用网格视图连接RowDataBound事件。

使用Default_Load事件时的代码

Private Sub _Default_Load(sender As Object, e As EventArgs) Handles Me.Load

... SQL Connection Stuff

Using dt As New DataTable()
sda.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()

'color rows based on some condition
For Each row As GridViewRow In GridView1.Rows
    If row.Cells(4).Text = "" Then
        row.Cells(4).BackColor = System.Drawing.Color.Red
    End If
Next

End Sub

使用RowDataBound事件时的代码

Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs)
    If e.Row.RowType = DataControlRowType.DataRow Then
        If e.Row.Cells(4).Text = "" Then
            e.Row.Cells(4).BackColor = System.Drawing.Color.Red
        End If
    End If
End Sub