Search code examples
c#asp.netdata-bindinglifecycle

Should I *really* be calling DataBind()?


I have a CustomControl that, when used on a page, needs to take as a property a value from a server-side value. I tried this ...

<MyControl runat="server"
           ID="MyControl1"
           ContainerId="<%= this.ClientID %>" />

Now, when run (for the sake of this explanation, lets say that I know the value of this.ClientID was "ctl00_MyControl1") if I test the value, client-side, of ContainerId it comes back as "<%= this.ClientID %>".

Without really understanding why, I tried this instead...

<MyControl runat="server"
           ID="MyControl1"
           ContainerId="<%# this.ClientID %>" />

But testing the value of ContainerId showed that the value was empty!

Some more reading enabled me to see that the <%# %> mechanism is for data binding but, clearly, my control wasn't doing that (assume that my CustomControl inherits from a TextBox).

So, I added a call to DataBind() to the OnLoad event of the UserControl that my CustomControl is contained in.

Yay! It worked. However, when processing certain events on the Page, the call to DataBind() generates an exception. The exception is in another control, contained in the same UserControl container as MyControl1.

The message is

Selection out of range
Parameter name: value

and the stack trace finishes like this ...

   at Telerik.Web.UI.RadComboBox.PerformDataBinding(IEnumerable dataSource)
   at Telerik.Web.UI.RadComboBox.OnDataSourceViewSelectCallback(IEnumerable data)
   at System.Web.UI.DataSourceView.Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback)
   at Telerik.Web.UI.RadComboBox.OnDataBinding(EventArgs e)
   at Telerik.Web.UI.RadComboBox.PerformSelect()
   at System.Web.UI.WebControls.BaseDataBoundControl.DataBind()
   at Telerik.Web.UI.RadComboBox.DataBind()
   at System.Web.UI.Control.DataBindChildren()
   at System.Web.UI.Control.DataBind(Boolean raiseOnDataBinding)
   at System.Web.UI.Control.DataBind()

Now, I'm not looking for a solution to this exception; I've included it to demonstrate that I believe that my calling DataBind() is not necessarily the right thing to do.

So, Questions:

  1. Why doesn't <%= %> give the value at runtime I expect?
  2. Is calling DataBind() whenever the UserControl's OnLoad event fires the right thing to do to get my value at runtime and, if it is,
  3. Are there conditions I should be checking for before calling DataBind()

Solution

  • "`<%= this.ClientID %>`"  
    

    is called at render time and ClientID has not been set at that moment.

    "`<%# this.ClientID %>`" 
    

    is called during the control or page DataBind(). If you are going to use this last one, then you should indeed call DataBind() and fix your exception.