Change Style of rows created by ListView in itemCreated event
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 my开发者_C百科RowView;
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
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...
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.
精彩评论