Search code examples
asp.netdatabaselinqprerender

Page Cycles - Right way to input data to database


I have a page that has a few textboxes and a dropdownlist. When a logged in user opens this page the boxes are filled with data that he has input before, he can change the data and update it by pushing a update button. There is also that dropdownlist which has a dynamically populated data for him to choose from.

What is the best way to make this page work. Where in the page cycles do I populate the forms and where do I input the data to the datatable.

At the moment I'm populating the data on PreRender but the dropdownlist on the preinit. I have a button event handler to do the update on the datatable. The problem is that the autopostback messes up the data in the dropdownlist because its dynamically populated, how would I go by fixing this?


Solution

  • Here is what I follow in most of my cases

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            InitDropdDownListes();
            LoadDataFromDataBase();
        }
    
    }
    
    void InitDropdDownListes()
    {
        // fill drop down boxes
    
    }
    
    void LoadDataFromDataBase()
    {
        // load from database
    
    }
    
    protected void OnDropdownListChanges(object sender, EventArgs e)
    {
        // reload the new data from database
        LoadDataFromDataBase();
    }
    
    
    protected void btnSave_Click(object sender, EventArgs e)
    {
        // Save to database
    
    }