user3809554
user3809554

Reputation: 143

Why SQL will only update the text boxes original text? ASP.Net

so the problem I'm having is that on my button click it's supposed to update the database with the values in the text boxes. These are being read in on the page load. Having modified the code a bit to see what's going on, even if the content of the text box is changed, it submits the original text. I can't wrap my head around why. I need it to submit any changes to those text boxes. Any help or guidance appreciated.

protected void Page_Load(object sender, EventArgs e)
        {
                    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
                    con.Open();

                    string checkic1 = "SELECT colum1 FROM table1 WHERE ID='1';";
                    SqlCommand c1Comm = new SqlCommand(checkic1, con);
                    string ic1 = c1Comm.ExecuteScalar().ToString();

                    con.Close();

                    c1TxtBox.Text = ic1;

        }

The example above is the same for c2TxtBox and c3TxtBox as well.

protected void Button1_Click(object sender, EventArgs e)
        {
                SqlConnection update = new   SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);


                string addUpdate= "UPDATE table1 SET colum1 = @c1, colum2 = @c2, colum3 = @c3 WHERE ID='1';";
                SqlCommand comA = new SqlCommand(addUpdate, update);

                comA.Parameters.AddWithValue("@c1", c1TxtBox.Text);
                comA.Parameters.AddWithValue("@c2", c2TxtBox.Text);
                comA.Parameters.AddWithValue("@c3", c3TxtBox.Text);

                update.Open();

                comA.ExecuteNonQuery();

                update.Close();

                Response.Redirect("originalPage.aspx");
            }
        }

Upvotes: 1

Views: 23

Answers (1)

Klaus Byskov Pedersen
Klaus Byskov Pedersen

Reputation: 120917

The PageLoad function is called everytime you load the page, also when you submit the page by clicking your button. Therefore, the value of the textbox is overwritten before you try to update your database (because PageLoad is called before Button1_Click).

To overcome this, you could add a check to see if you are currently in a post back in your PageLoad method, like this:

protected void Page_Load(object sender, EventArgs e)
{
    if(!this.IsPostBack)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
        con.Open();

        string checkic1 = "SELECT colum1 FROM table1 WHERE ID='1';";
        SqlCommand c1Comm = new SqlCommand(checkic1, con);
        string ic1 = c1Comm.ExecuteScalar().ToString();

        con.Close();

        c1TxtBox.Text = ic1;
    }
}

Upvotes: 1

Related Questions