开发者

Selecting item in incapsulated DropDownList on DataBind

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;
   }
}开发者_JS百科

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:

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜