Search code examples
c#sqlasp.netsql-server-2014-express

ASP.net unable to UPDATE column in SQL Server


I'm creating an online application where I'm trying to update data through asp.net winforms. I have a textbox named tbCompanyName and a column in my database named companyName, in table tblCompanySetup.

I'm SELECTING previous data from column perfectly, but when I try to update data, it is not updating data, although don't showing any errors. I have worked in C# desktop application, but I'm completely newbie in ASP.NET.

I think there may be any AUTOPOSTBACK issues, but I don't know how to resolve. I'm posting my code that I'm using for updating the data in a SQL Server table. Help me please.

using (var con = new SqlConnection(ConStr))
{
    string query = @"UPDATE tblCompanySetup SET companyName = @companyName";

    using (var cmd = new SqlCommand(query, con))
    {
        con.Open();
        cmd.Parameters.AddWithValue("@companyName", SqlDbType.NVarChar).Value = tbCompanyName.Text;
        cmd.ExecuteNonQuery();
    }
}

NOTE: I have previous value in textbox that I'm using for a new value to update. It's working fine when I put that textbox empty and type new value. But when I select previous value in textbox and then input new value and click submit, it is actually saving the previous value I guess.. Also when I press the submit button, it refreshes the form and put the previous value again


Solution

  • It seems that you have retrieving method from a database on a page load. Something like:

    protected void Page_Load(object sender, EventArgs e){
        RetrieveMyData(); // it is a method where you retrieve a data
    }
    

    Change this to:

    protected void Page_Load(object sender, EventArgs e){
        if (!IsPostBack)
            RetrieveMyData(); // it is a method where you retrieve a data
    }
    

    Your project works like:

    1) Page_Load -> RetrieveMyData()

    2) Your textbox has some value from a database

    3) You changing that value to a new value

    4) You click on a UPDATE button

    5) As you don't consider PostBack, it calls again RetrieveMyData and your textbox has the old value

    6) Your Update method executes, but no changes occurs

    If you will use PostBack as I showed:

    1) Page_Load -> RetrieveMyData

    2) Your textbox has some value from a database

    3) You change that value

    4) You click on a Update button

    5) As you use !IsPostBack and button occur a postback, your RetrieveMyData method will not work here

    6) Your update method will update the old value with a new one

    Hope it helps