.net – Referencing code-behind properties on .aspx page

asp.netcode-behindnetvb.net

On a .aspx page, what is the best way to link a server control's property to a property of the page class (its code-behind)? The only way that I have read about is to use databinding:

<asp:TextBox ID="txt" runat="server" Text='<%# Me.SomePropOfMine %>' />

and then call Me.txt.DataBind() or Me.Databind() from the codebehind. Is there any way of establishing this relationship on the .aspx page alone, or simplifying the process if you have many controls to bind (without binding the entire page)?

Best Answer

You can Databind() entire Me or a container control (you can add a PlaceHolder control around your desired controls also). because DataBind() goes recursively on Child controls.

A better approach if you don't need DataBinding except for this is to use Code Expression Binder

http://weblogs.asp.net/infinitiesloop/archive/2006/08/09/The-CodeExpressionBuilder.aspx

This allows you to use <%$ Code: Me.Property %> instead of <%# Me.Property %>.

For more about expression builders in general if you don't know them at all check this intro post: http://www.4guysfromrolla.com/articles/022509-1.aspx

Note that <%= Me.Property %> will NOT work on web controls like <asp:TextBox ... and such...

P.S.

The only drawback with Code expression builder is that you get no intellisense. I usually work around this by writing <%= Me.TestSomething %> inside the markup to get my intellisense, and then replace <%= with <%$ Code: when done. Annoying, but if you don't want to go the DataBind() route (and you shouldn't cause it may conflict with existing real data binding you want to do. Trust me, trying to make those work is hell), then this is the way to go.

Related Topic