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

D

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.
 
C

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top