how to have listview row colour to change based on data in the row
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)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) _
Hand开发者_如何学JAVAles 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
Many thanks for your help.
dk
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">
...
A different (and IMO, simpler) approach will be using data-binding expressions. For example, in your markup, use
<ItemTemplate>
<tr class='<%# GetRowStyle(Container.DataItem) #>'>
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";
}
}
And lastly, define those css classes (row, altRow) as per your needs.
and without any code behind at all.
I just added another field to the SQL called status for example
select given, surname, case when owing > 1000 then 'Behind' else 'OK' end as Status from cust
then in the page
<ItemTemplate>
<tr class='<%# Eval("Status") %>' style="">
and
<style type="text/css">
.behind
{
font-style :italic ;
color: black ;
}
.ok
{
color: grey ;
}
</style>
I know this is old but if anyone looking for inline without css (like I was) here is my solution:
The db column 'Priority' contains 0,1,2, etc.. and i want to color my list rows red,blue,green according to those :
<ItemTemplate>
<div style='<%# color:" + mylistof_PRIORITYCOLORS[Convert.ToInt16(Eval("Priority"))] %>'>
and your list defined
public static List<string> mylistof_PRIORITYCOLORS = new List<string> { "Red", "Blue", "Green" };
精彩评论