Wednesday, May 6, 2009

Binding a control property to a code-behind property or method.

In ASP.NET often it is easier to bind a code-behind property with a control property instead of using FindControl() method to find the control on the page and set it through code. It is also less bound to where the control you are trying to work with is on the page, which means less bugs and less maintenance issues.

Let’s assume you have a button on the page that you want to show or hide based on some logic you have on your code-behind class or maybe in a static class or singleton class you can access in one line of code. You can bind to it from the .aspx or .ascx page.

Here are some examples of how we could bind the code-behind property Test to the Visible property of the button. The Visible property will only be updated when the container of this button is databound. This is usually done with the DataBind() method.

<asp:LinkButton ID="LinkButton1"runat="server"Text="Submit"Visible="<%# Test %>"/>

<asp:LinkButton ID="LinkButton1" runat="server" Text="Submit" Visible=’<%# Test %>’/>

Do NOT do the following (use equal sign instead of number sign), because it will NOT work.

<asp:LinkButton ID="LinkButton1" runat="server" Text="Submit" Visible=’<%= Test %>’/>

<asp:LinkButton ID="LinkButton1" runat="server" Text="Submit" Visible="<%= Test %>"/>

Let’s assume in the code-behind you have a property called Test. It would look something like one of these, but with more logic.

protected bool Test { get { return true; } }
protected Boolean Test { get { return true; } }

The property can be protected or public, but cannot be private because private properties in the code-behind are not visible to the .aspx or .ascx page. It is important that the return type match what the control property is expecting

You can also do the same thing (same variations apply), but use a method instead of a property in the code-behind.

<asp:LinkButton ID="LinkButton1"runat="server"Text="Submit" Visible="<%# Test2() %>"/>

<asp:LinkButton ID="LinkButton1" runat="server" Text="Submit" Visible=’<%# Test2() %>’/>
public bool Test2() { return true; }

If you don’t want to create a bunch of properties, you can also use standard code also.

<asp:LinkButton ID="LinkButton1" runat="server" Text="Submit" Visible=’<%# MyMode != “ReadOnly” && OtherConditional %>’/>


1 comment:

Blogger said...

Are you trying to make money from your visitors by using popunder ads?
In case you do, did you try using PropellerAds?