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