Christopher Garcia
Christopher Garcia

Reputation: 2544

Inconsistencies When Accessing DataBound Item Controls

Essentially, my question is this: There are two ways that I have experienced setting values to databound controls. Either this way:

<asp:Label runat="server" id="MyLabel"><%#DataBinder.Eval(Container.DataItem, "MyValue")%></asp:Label>

Or this way:

<asp:Label runat="server" id="MyLabel" text=<%#DataBinder.Eval(Container.DataItem, "MyValue")%> />

When trying to access items in an event handler (outside of the method that this databinding is occuring) using the first method, MyLabel.Text is an empty string. However, using the second way, MyLabel.Text will equal "MyValue". Can anyone tell me why this happens?

Upvotes: 1

Views: 148

Answers (2)

Julien Poulin
Julien Poulin

Reputation: 13025

Not sure about this but... It may be because in the second example, Text is a property of the Label control and you set it directly, whereas in the first example, you're not setting the Text property, you're just adding a child to the Label...

EDIT: A quick look with Reflector confirmed this: if the Label has some child content to it, it is that content that is rendered to html (but it's never set to the Text property). Otherwise, it is the content of the Text property that is rendered.

Upvotes: 0

Scott Ivey
Scott Ivey

Reputation: 41558

The Text property of a Label doesn't map to the inner text in the control markup. The Label control can be used as a container for other controls - so you'd put child controls inside the tag.

The reason you're seeing the Text as empty when you bind using <%# ... %> is because the bound text is rendering as a child literal control in the MyLabel.Controls collection. In this case, you'd access the text as

var myText = ((ITextControl)MyLabel.Controls[0]).Text;
// instead of..
var myText = MyLabel.Text;

If you want to access the Text of the label - always use the Text property. If you want to nest controls in your label - put them between the markup tags.

Upvotes: 1

Related Questions