2017-10-20 53 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

相關問題