Question

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?

Thanks!

Was it helpful?

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

OTHER TIPS

It's explained by a concept called viewstate:

If you examine the code produced by your asp, you will find some hidden fields, one of which is the "viewstate". The viewstate saves the important values of your asp in order to be able to populate the elements every time the pages gets loaded, even if it's after a postback.

The data is maintained during postback, as you don't clear the data during postback or on load it will persist.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top