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!
DataBinding always occurs before
PreRender. From ASP.Net Page Lifecycle:One solution to your issue would be to just handle the
DataBindingevent and pre-bind your dropdownlist (or even just do it duringLoad), rather than waiting all the way untilPreRender. This would ensure that theDropDownListwas 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 duringPreRender, by accessing the datasource.