jacek_podwysocki
jacek_podwysocki

Reputation: 807

Update form keeps original values

I have a form which is filled with values retrieved from database. That form has a submit button which should update the corresponding fields in the database once clicked.

The problem is that no matter what I do the values do not get updated in the database. I'm using a stored procedure and checked it twice, it works ok, I also tried the trick with the hardcoded insert value-also works.

My guess is that once the field is populated from the database on Page_Load, its value remains even if I change it. How do I overcome this issue so that I can use the same form to retrieve and update data?

 protected void Page_Load(object sender, EventArgs e)
    {
        lblMsg.Visible = false;

        string bookingid = Request.QueryString["bookingid"];
        Booking b = BookingAccess.GetBooking(Int32.Parse(bookingid));
        if (b != null)
        {
            var start_date_formatted = ((DateTime)b.StartDate).ToString("dd-MM-yyyy");
            var end_date_formatted = ((DateTime)b.EndDate).ToString("dd-MM-yyyy");

            pet_name.Text = b.PetName;
            species.Text = b.Species;
            start_date.Text = start_date_formatted;
            end_date.Text = end_date_formatted;
        }


    }

    protected void btnEditBooking_Click(object sender, EventArgs e)
    {
        string bookingid_raw = Request.QueryString["bookingid"];
        int bookingid = int.Parse(bookingid_raw);

        var start_date_formatted = DateTime.ParseExact(start_date.Text, "dd-MM-yyyy", null);
        var end_date_formatted = DateTime.ParseExact(end_date.Text, "dd-MM-yyyy", null);

        string pet_name = "a";
        string species = "b";
        lblMsg.Visible = true;
        string msg = BookingAccess.UpdateBooking(bookingid, pet_name, species, start_date_formatted, end_date_formatted);
        if (msg == null)
            lblMsg.Text = "Updated booking details successfully!";
        else
            lblMsg.Text = "Error -> " + msg;
    }

Upvotes: 0

Views: 78

Answers (1)

Kami
Kami

Reputation: 19457

If you have your data load in the Page_Load function, ensure that you are checking for IsPostBack to ensure that you do not reset the data when the user submits the page.

private void Page_Load()
{
    if (!IsPostBack)
    {
        // Load the data from database
    } else {
        // Validate the data and save to database
    }
}

Upvotes: 1

Related Questions