views:

110

answers:

1

I have a complex UserControl with the main purpose to encapsulate DropDownList with a number of properties for advanced manipulation.

List is being populated on PreRender event depending on properties previously were set:

protected void Page_PreRender(object sender, EventArgs e)
{
    sourceClient.SelectCommand = this.Property1 ? "exec a" : "exec b";
}

The most used property is ClientID:

[Category("Settings")]
public int ClientID
{
   get
   {
      return Int32.Parse(DropDownList1.SelectedItem.Value);
   }
   set
   {
      DropDownList1.Items.FindByValue(value).Selected = true;
   }
}

Getter commonly is being called by ControlPameters in SqlDataSources on pages with this control.

Setter - from markup: <uc:UserControl1 runat="server" ClientID='<%# Bind("ID") %>' />.

So the question is:

Why does setter from Bind is called earlier then PreRender? And DropDownList is empty and item selecting doesn't work! How to workaround this behavior?

Edit1: Ok, not PreRender but Init. But DropDownList1_DataBinding is still being called after property setter!

+1  A: 

DataBinding always occurs before PreRender. From ASP.Net Page Lifecycle:

DataBinding
This event is raised by data-bound controls before the PreRender event of the containing control (or of the Page object) and marks the beginning of binding the control to the data.

Use this event to manually open database connections, if required. (The data source controls often make this unnecessary.)

One solution to your issue would be to just handle the DataBinding event and pre-bind your dropdownlist (or even just do it during Load), rather than waiting all the way until PreRender. This would ensure that the DropDownList was available when the Bind call goes off.

Another solution would be to just pass your control a reference to the datasource itself, rather than using a Bind call. Then it could programmatically deal with binding itself at the right times - you could load your DropDownList, and then get your ID for it, all during PreRender, by accessing the datasource.

womp
@womp: Hi, thanks for tips! I rewrote my code so now I have Page_DataBinding event handler but still first is called Page_DataBinding after it property setter and after it DropDownList1_DataBinding where it it's being populated from a data source. How to data bind drop down list before setter?
abatishchev