Home All Groups Group Topic Archive Search About

Unhappy call to a 2nd dataItem in ItemTemplate of an asp:TemplateC

Author
1 Jul 2005 9:52 AM
Didg
I have a working page with this snippet inside an asp:TemplateColumn
cheerfully returning data:

<ItemTemplate><asp:Label runat="server" BackColor="LightGreen" Text='<%#
DataBinder.Eval(Container, "DataItem.Region") %>'>...

Now I want to set the BackColor, so I create a new DataItem property, test
it and this works very finely:

<asp:Label runat="server" BackColor="LightGreen" Text='<%#
DataBinder.Eval(Container, "DataItem.RegionColor") %>'>

so then I use:

<asp:Label runat="server" BackColor='<%# DataBinder.Eval(Container,
"DataItem.RegionColor") %>' Text='<%# DataBinder.Eval(Container,
"DataItem.Region") %>'>

but unhappiness.

Any explanation/solution received with joy.

Author
1 Jul 2005 3:44 PM
cc
Basically, it has to do with the Asp.Net page lifecycle: all of the
style properties get set before the databinding occurs, so your attempt
to set the BackColor during databinding fails. I
You _can_ do what you want, however: in the page code-behind file, set
up an eventhandler for the DataGrid's ItemDataBound event. Inside the
eventhandler method, set your BackColor property like you want. You'll
have to use the FindControl method to locate your label. The code would
looking something like this using C#:

Label lbl = e.Item.FindControl("myLabelID") as Label;

Once you've located your label control, just call its BackColor
property. You can get to the current DataRow that's being bound via the
current DataGridItem's DataItem property. Again, in C#:

if ( lbl != null ) // make sure you've actually found the control
{
// assumes you're binding to a DataSet
lbl.BackColor = ((e.Item.DataItem as DataRowView).Row as
MyStronglyTypedDataRow).RegionColor;
}

Finally, a much easier way to accomplish what you want using this same
technique--instead of the Label--would be to set the e.Item.BackColor
property. That way you don't have to search for the Label control.

Good luck. Hope that helps.