drdwilcox
drdwilcox

Reputation: 3951

WebForms: DataBind to Text Property of derived CheckBox control

I have a page which has a CheckBox control as such:

<asp:CheckBox ID="Save" runat="server" Text='<%= SomePageMethod("param") %>' />

This works just fine, the SomePageMethod is called and the page renders the correct text next to the check box.

Now, we are doing some work on testing WebForms pages, and as part of this work, we build a trivial derived class so we can inject an interface:

namespace MyControls
{
    public interface ICheckBox
    {
        bool Visible { get; set; }
    }

    public class CheckBox : ICheckBox, System.Web.UI.WebControls.CheckBox
    {
    }
}

I then import the class onto my page thus:

<%@ Register Namespace="MyControls" Assembly="MyControls" TagPrefix="vm" %>

And change the control definition to:

<vm:CheckBox ID="Save" runat="server" Text='<%= SomePageMethod("param") %>' />

Now, the data binding expression is never called and so my check box has no text.

Any ideas why this wouldn't work? Nearly everything else we have done with these controls is working perfectly, but this one has me stumped.

Note: Edited to remove the ambiguity of having the Checked property in the made-up interface.

Upvotes: 1

Views: 61

Answers (1)

Mark Davich
Mark Davich

Reputation: 626

Could it be as simple as calling data bind on the page? I created a small test that mirrors your requirements, and the text wasn't bound until I explicitly called DataBind() on the page or individually on each control.

Below is an example of an ASP CheckBox and a custom CheckBox which implements ICheckBox

TestPage.aspx

...
<vm:CheckBox ID="VmCheckBox" runat="server" Text="<%# GetCheckBoxText(23)%>"/>
<asp:CheckBox ID="AspCheckBox" runat="server" Text="<%# GetCheckBoxText(23)%>" />

NOTE that I used # instead of = in the binder, i.e., <%# ... %>

TestPage.aspx.cs

...
protected void Page_Load(object sender, EventArgs e)
{
    DataBind() // Binds all objects on page
    
    // ...Or individually bind controls
    VmCheckBox.DataBind()
    AspCheckBox.DataBind()
}

Upvotes: 1

Related Questions