C# – Dropdown binding and postbacks – ASP.NET

asp.netc

I have a rather complex page. The ASPX page loads a user control which in turn loads a child User control.

Parent Control

protected override void OnInit(EventArgs e)
{
  //Loads child control
}

In the child user control, I use custom control that inherits from System.Web.UI.HtmlControls.HtmlSelect

ASCX:

<cust:CustDropDownList id="ctlDdl" runat="server"/>

ASCX.CS

protected void Page_Load(object sender, EventArgs e)
{
  //Binds CtlDdl here 
}

When the user clicks on the Save button, the controls get user controls get dynamically reloaded, but Iose the value the user has selected in the dropdown. I run into the chicken and egg problem here.

I think I need to bind the ctlDdl only on if its not a postback, but that results in the dropdown not getting populated.

If I bind it everytime, then i lose user's selection

EDIT:
Can someone respond to my comment to Jonathan's answer? Thanks

Best Answer

With custom controls, you have to manage the state. There is a sort of bubble-up effect where the state is passed along. If you don't deal with it, you don't get state.

This link will get you started: Server Control Custom State Management

Look for

    Protected Overrides Sub LoadViewState( _
        ByVal savedState As Object)
        Dim p As Pair = TryCast(savedState, Pair)
        If p IsNot Nothing Then
            MyBase.LoadViewState(p.First)
            CType(Author, IStateManager).LoadViewState(p.Second)
            Return
        End If
        MyBase.LoadViewState(savedState)
    End Sub

at Custom Property State Management Example

Related Topic