如何使listview行颜色根据行中的数据进行更改

问题描述:

我遵循了这个问题在基于数据库条目的ASP.NET中的列表视图中,在运行时更改了每行的颜色并尝试在VB中执行相同的操作,但是我遇到了一些无法解释的错误,例如对象引用未设置为对象的实例 此行最有可能=>
HtmlTableRow = DirectCast(e.Item.FindControl("MainTableRow"),mlTableRow)的昏暗单元格

I followed this question stuck on changing each row color during run-time in listview in asp.net based on database entries and tried to do the same in VB but i am getting some unexplained errors, like Object reference not set to an instance of an object most likely for this row =>
Dim cell As HtmlTableRow = DirectCast(e.Item.FindControl("MainTableRow"), mlTableRow)

请让我知道在VB中是否有更好的方法/正确的方法?

Please let me know if there is any better way / correct way to do this in VB?

Protected Sub ListView2_ItemDataBound1(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewItemEventArgs) _
Handles ListView2.ItemDataBound
    If e.Item.ItemType = ListViewItemType.DataItem Then
        Dim dataitem As ListViewDataItem = DirectCast(e.Item, ListViewDataItem)
        Dim mstorename As String = DataBinder.Eval(dataitem.DataItem, "Store")
        If mstorename = "A1" Then
            Dim cell As HtmlTableRow = DirectCast(e.Item.FindControl("MainTableRow"), mlTableRow)
            cell.BgColor = #E0E0E0
        End If
    End If
End Sub

非常感谢您的帮助.

dk

为此,您必须确保为tr元素提供MainTableRow id并将其标记为runat="server",即确保您的标记-up(html)就像

For this to work, you must ensure that you provide MainTableRow id to tr element and mark it as runat="server" i.e. make sure that your mark-up (html) is something like

<ItemTemplate>
   <tr id="MainTableRow" runat="server">
   ...

一种不同的方法(也是IMO,更简单)将使用数据绑定表达式.例如,在您的标记中,使用

A different (and IMO, simpler) approach will be using data-binding expressions. For example, in your markup, use

<ItemTemplate>
       <tr class='<%# GetRowStyle(Container.DataItem) #>'>

在代码背后,有一个受保护的函数可以提供基于数据的CSS类(示例为c#函数)

And in code-behind, have a protected function to provide CSS class based on data (a example c# function will be)

protected string GetRowStyle(object item)
{
   var store = DataBinder.Eval(item, "Store");
   if (store == "A1")
   {
      return "altRow";
   }
   else
   {
     return "row";
   }
}

最后,根据需要定义这些CSS类(row,altRow).

And lastly, define those css classes (row, altRow) as per your needs.