asp.netlifecyclepage-lifecycle

How is this explained with ASP.NET page life cycle?


I have the following code, which simply inserts a record into the database, based on some text fields and a dropdown. The dropdown gets bound in the Page Load Event.

protected void btnAdd_Click(object sender, EventArgs e)
{
    try
    {
        Personeel p = new Personeel();
        p.achternaam = txtNaam.Text;
        p.naam = txtVoornaam.Text;
        p.fk_afdeling_id = Convert.ToInt16(cmbAfdeling.SelectedValue);

        BLLpersoneel BLLp = new BLLpersoneel();
        BLLp.insert(p);
        lblFeedback.Text = "Done and done!";
        rptPersoneel.DataBind();
    }
    catch (Exception err)
    {
        lblFeedback.Text = err.Message;
    }
}
protected void Page_Load(object sender, EventArgs e)
{
    if(Page.IsPostBack == false)
    { 
    BLLafdeling BLLa = new BLLafdeling();
    cmbAfdeling.DataSource = BLLa.selectAll();
    cmbAfdeling.DataTextField = "naam";
    cmbAfdeling.DataValueField = "afdeling_id";
    cmbAfdeling.DataBind();
    }
}

My question is about IsPostBack. On first load, the page has no PostBack, so it will bind the data to the dropdown "cmbAfdeling".

Then, when submitting the form, there IS a postback, so we don't reach the code inside the if statement. To me, that would mean that ASP.NET would NOT bind the data to the combo box.

However, the data is still there after submitting (and thus having a postback).

How is this explained?


Solution

  • This is due to the ViewState. The data in the ComboBox is stored in the ViewState and is sent back & forth during postback.

    This might be worth reading to understand what is happening: http://msdn.microsoft.com/en-us/library/ms972976.aspx