Wednesday, July 15, 2009

How to highlight a particular row in a datalist based on some condition in ASP.NET?

I have a datalist bound to a database. I want to highlight the rows of the datalist if the date in the database column is less than today's date in the output. How to go about it?

How to highlight a particular row in a datalist based on some condition in ASP.NET?
Depends how you have your DataList laid out.





I would use the OnItemDataBound event to dictate the background of the item.





Sub dlStuff_onItemDataBound(Sender As Object, E As EventArgs)


Dim dtTarget As DateTime = Now()


If E.Item.ItemType = ListItem.Item Or E.Item.ItemType = ListItem.AlternatingItem Then


Dim dtTemp = Convert.ToDateTime( (CType(E.Item.DataItem, DataRowView) ).Row.ItemArray(1).ToString())





If dtTemp %26lt; dtTarget Then


E.Item.BackColor = "Yellow"


End If


End If


End Sub





%26lt;asp:DataList


id="dlStuff"


runat="server"


BorderColor="black"


CellPadding="5"


CellSpacing="0"


RepeatDirection="Vertical"


RepeatLayout="Table"


RepeatColumns="3"


OnItemDataBound="dtStuff_onItemDataBou...


%26lt;HeaderTemplate%26gt;


List of items


%26lt;/HeaderTemplate%26gt;





%26lt;ItemTemplate%26gt;


Name:






%26lt;%# DataBinder.Eval(Container.DataItem, "Name") %%26gt;






Date:






%26lt;%# DataBinder.Eval(Container.DataItem, "Date", "{0:d}") %%26gt;


%26lt;/ItemTemplate%26gt;


%26lt;/asp:DataList%26gt;
Reply:You should write code in the ItemDataBound event handler of the DataList.





private void dl_ItemDataBound (object sender,


System. Web. UI. WebControls. DataListItemEventArgs e) {


DataRowView drv = (DataRowView) (e.Item. DataItem);


DateTime date = DateTime( drv. Row["DateField"]. ToString() );


if ( date %26lt; 10 ) {


e.Item.BackColor = Color.Red;


}


}





PS~The above code uses the same approach in VB.NET however it contains a mistake. The e.Item.BackColor is of type System.Drawing. Color not System.String. You cannot assign the string "yellow" to it.
Reply:IN the datalist properties look for the style section


In the selectedItemStyle change the back color to your highlight color.





that should get you close...hope it helps

rose garden

No comments:

Post a Comment