During page processing, the DataList control creates individual items that it will render to the page. To allow you to customize the items as they are being created, the DataList control raises an event. By responding to this event, you can change the items. A typical use is to change the appearance of the item based on the data being displayed in it. For example, if a numeric value you read from a database is negative, you might set the item's background color to red.
To customize items at run time
[Visual Basic] Private Sub DataList1_ItemCreated(ByVal sender as Object, _ ByVal e as DataListItemCreatedEventArgs) [C#] protected void DataList1_OnItemCreated(Object sender, DataListItemCreatedEventArgs e)
Note The OnItemCreated event is raised for all items in the list, including the header and footer. (The event is raised for these items even if you did not create templates for them, in case you want to create them dynamically.) If you do not want to handle the event for certain item types, you can test for those types, as explained in the next step.
Note The ItemIndex property returns a positive value only for Item, AlternatingItem, and SelectedItem objects only. The index value for header, footer, and separator items is -1.
The following example shows how you can modify the background color of an item conditionally. The example uses the ItemType property to make sure that the template being rendered is not a header, footer, or separator. It then determines what item number is being rendered. If it is an even-numbered item (that is, if the modulus of the item index and 2 is zero), the method sets the item's background color to yellow. To show its progress, the method displays a message in a Label Web control for every item it creates.
[C#]
protected void DataList_OnItemCreated(object Source, DataListItemCreatedEventArgs e)
{
if( e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem){
if ( (e.Item.ItemIndex % 2) == 0 ){
e.Item.BackColor = Color.LightGoldenrodYellow;}
Label1.Text = Label1.Text + "Creating item " + e.Item.ItemIndex
+ " (" + e.Item.ItemType + ")" + "<BR>";
}
}
At the time that the OnItemCreated event is raised, the individual controls in the templates have not yet been bound to data. You therefore cannot base a condition on the bound data for a control. However, the data is available, and you can use a data-binding expression to extract the data that will be bound to the control and base a comparison on that.
The following example shows how you can make a conditional test based on data. The example extracts a field — the Quantity field — from the current record from the data source. If the quantity is less than zero, the item in the DataList control is colored red.
[C#]
protected void DataList_OnItemCreated(object Source,
DataListItemCreatedEventArgs e)
{
if( ((Int32)DataBinder.Eval(e.Item.DataItem, "Quantity")) < 0){
e.Item.BackColor = Color.Red;
}
}