我有一个GridView1,显示我公司正在建造的当前机器尚未发货。每行的Cell0显示机器的序列号。数字以[.000]表示机械或[.00E]表示电气。在机械产品中,它们分为四类 - [STD],[BLD],[TLG]和[DIE]。 GridView1没问题。
我正在使用Visual Studio 2010,在VB中编码,而不是C#。我根据机器是[.000]还是[.00E]以及它所属的类别 - [STD],[BLD],[TLG]或[DIE]对cell0的背景进行颜色编码。一切都有效,颜色可以对应。什么行不通的是我无法在cell0背景中获得最后一卷GridView1的颜色。它仍然是白色的。
我没有正确关闭或忘记最后的代码吗?
这是魔术发生的代码。
If e.Row.RowType = DataControlRowType.DataRow Then
For Each er As GridViewRow In GridView1.Rows
'Get the Serial Number out of the first column
Dim TrimmedJN As String
TrimmedJN = Trim(er.Cells(0).Text)
Session("JNPerRow") = TrimmedJN
SqlDataSource4.DataBind()
GridView_Code.DataBind()
Dim TrimmedCode As String
TrimmedCode = GridView_Code.Rows(0).Cells(0).Text
If TrimmedJN.EndsWith("00") And TrimmedCode = "TLG" Then
er.Cells(0).BackColor = Drawing.Color.Orange
ElseIf TrimmedJN.EndsWith("00") And TrimmedCode = "BLD" Then
er.Cells(0).BackColor = Drawing.Color.Orange
ElseIf TrimmedJN.EndsWith("00") And TrimmedCode = "DIE" Then
er.Cells(0).BackColor = Drawing.Color.Pink
'Makes everything else light green
Else : er.Cells(0).BackColor = Drawing.Color.LightGreen
End If
'Overrides the green to be yellow for Electrical
If TrimmedJN.EndsWith("0E") Then
er.Cells(0).BackColor = Drawing.Color.Yellow
End If
Next
End If
答案 0 :(得分:0)
你在RowDataBound
事件中有一个嵌套循环(我假设这是代码片段的内容)。
For Each er As GridViewRow In GridView1.Rows
RowDataBound事件已遍历所有单元格。因此,当RowDataBound事件处理最后一行时,它还不是GridView行集合的一部分,因此嵌套循环无法找到它。
最好是在RowDataBound事件中使用源数据进行比较。
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
'check if the row is a datarow
If (e.Row.RowType = DataControlRowType.DataRow) Then
'cast the row back to a datarowview
Dim row As DataRowView = CType(e.Row.DataItem,DataRowView)
'get the cell value not from the gridview, but from it's source data
Dim cellValue As String = row("myColumn").ToString
'color cells or rows
e.Row.BackColor = Color.Red
e.Row.Cells(0).BackColor = Color.Green
End If
End Sub