J.Steve
J.Steve

Reputation: 7319

Referencing code-behind properties on .aspx page?

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

Upvotes: 4

Views: 9721

Answers (3)

Meligy
Meligy

Reputation: 36594

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: https://web.archive.org/web/20210304125044/https://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.

Upvotes: 6

Loki Kriasus
Loki Kriasus

Reputation: 1301

If I would ever actually need to do this, I would use CodeExpressionBuilder.

But question is - why do you want to set properties in markup and not in code behind? If they are dynamic and related to logic (and probably they are), then you should set them in code behind even if that looks unconvenient - that would keep logic in one place and markup in other.

Upvotes: 0

drhanlau
drhanlau

Reputation: 2527

There are two things:

  1. Use <%= instead of <%# if you want to read the values of some variables.
  2. You can use Page.DataBind() to bind all the controls in the page.

Upvotes: 3

Related Questions