2017-10-20 55 views
0

我有一个GridView1,显示了我公司正在构建的尚未发布的当前计算机。每行的Cell0显示机器的序列号。该号码以机械[.000]或电气[.00E]结尾。在机械产品中,这些产品分为四类[STD],[BLD],[TLG]和[DIE]。 GridView1没有问题。GridView的最后一行的单元格将不会着色

我使用Visual Studio 2010,编码在VB中,而不是C#。我根据机器是[.000]还是[.00E]以及它属于什么类别 - [STD],[BLD],[TLG]或[DIE],对cell0的背景进行颜色编码。一切正常,使颜色对应。什么不起作用是我无法得到GridView1的最后一卷在cell0背景中着色。它仍然是白色的。

我没有正确关闭或忘记代码?

下面是魔术发生的代码。

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

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

试过了代码,它一开始并没有工作。然后我意识到,我从15个字符中提取了识别序列号(我们称之为工作号)的列,并且可能在其中包含了额外的空格,这就使得识别它是如何结束(00或0E)错误的。我做了一个简单的修剪[Dim cellValue As String = trim(row(“JOBNUM”)。ToString)],它像一个魅力一样工作。它甚至解决了另一个相关报告的报告问题。你,我的朋友是天才。十分感谢你的帮助。 – CVensel

相关问题