views:

147

answers:

2

Hi,

When render a databound ListView I want to dynamically set the background colour of each row depending on the results, in my case Red, Orange and Green.

        protected void ListView1_ItemCreated(object sender, ListViewItemEventArgs e)
    {
        DataRow myRow;
        DataRowView myRowView;
        myRowView = (DataRowView)e.Item.DataItem;
        myRow = myRowView.Row;

        if (myRow[2].ToString().CompareTo("") == 1)
        {
          // Colour coding here..    
        }

    }

Is it possible to reach the TR tag for each row to change the style?

Many thanks, Stefan

+1  A: 

Hey,

The TR tag would have to have runat="server" to use server-side code; however, you may be able to inject it in without that by examining the controls that are the child of the item; there's probably a Literal or LiteralControl with the HTML, and you can use string manipulation to inject...

Brian
Hi, do you mean by using the Sender or the ListViewItemEventArgs in ItemCreated event? Not 100% sure what you suggesting here. //Thanks
StefanE
if you use a server side TR, use e.Item.FindControl("trid"); otherwise, I'm not 100% sure, but I think the e.Item has a Controls collection, which you could loop through looking for the literal with the <TR> tag to inject.
Brian
A: 

I worked out a solution to my problem, with some good help from Brian.

I have a ListView and I added an id tag (trRow) and tag runat="server" like this:

<AlternatingItemTemplate>
            <tr id="trRow" runat="server" style="background-color:#FFF8DC;">

In code behind it looks like this:

        protected void ListView1_ItemCreated(object sender, ListViewItemEventArgs e)
    {
        DataRow myRow;
        DataRowView myRowView;
        myRowView = (DataRowView)e.Item.DataItem;
        myRow = myRowView.Row;

        System.Web.UI.HtmlControls.HtmlTableRow myTR = (System.Web.UI.HtmlControls.HtmlTableRow)e.Item.FindControl("trRow");

        if (myRow[2].ToString().CompareTo("") == 1)
        {
            myTR.Style.Value = "background-color:#FF0000;color: #000000;";
        } else
            myTR.Style.Value = "background-color:#00FF00;color: #000000;";

    }

Some of the logic in there is still not correct etc, just to show how I solved the issue to dynamically change the background color of each row.

StefanE