Chow.Net
Chow.Net

Reputation: 593

Update database table based on textbox values

I am trying to update database table based on text-box values.But i am unable to get new modified values in database.

Here is my code which displays information in text-boxes coming from database

protected void Info()
{
    string sID = Request.QueryString["ID"];
    string sSql = "select * from [fn_Items]('"+sID+"')";
    DataTable tbl1 = new DataTable();
    string sEr = myClass.FillupTable(sSql, ref tbl1);
    if (tbl1.Rows.Count > 0)
    {
        DataRow rd = tbl1.Rows[0];
        txtName.Text = rd["Name"].ToString();
        txtCategory.Text = rd["Category"].ToString();
        DateTime mStart;
        DateTime mFinish;
        Boolean b = false;

        b = DateTime.TryParse(rd["start"].ToString(), out mStart);
        b = DateTime.TryParse(rd["end"].ToString(), out mFinish);
        txtStart.Text = mStart.ToString("dd-MMM-yyyy");
        txtend.Text = mFinish.ToString("dd-MMM-yyyy");
        txtDescription.Text = rd["Description"].ToString();

    }
}

Now when the user modifies the text-box data and clicks save, the data should change in the database. Here is my click_event:

protected void btnSave_Click(object sender, EventArgs e)
{
    using (SqlConnection sqlConn = new 
        SqlConnection("Data Source=MSSQLSERVER2008;Initial Catalog=Items_2;Persist Security Info=True;User ID=sa;Password=password"))
    {

        string query = "UPDATE tbl_Items SET Name = @Name,Category=@Category,start = @start, end = @End,Description = @Description where ID = @ID ";
        SqlCommand cmd = new SqlCommand(query, sqlConn);
        cmd.Parameters.AddWithValue("@ID",txtID.Text);
        cmd.Parameters.AddWithValue("@Name", txtName.Text);
        cmd.Parameters.AddWithValue("@Category", Category.Text);
        cmd.Parameters.AddWithValue("@start", txtStart.Text);
        cmd.Parameters.AddWithValue("@end",txtend.Text);
        cmd.Parameters.AddWithValue("@Description", txtDescription.Text);
        cmd.Connection.Open();
        try
        {
            cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            throw new Exception("Error " + ex.Message);
        }

    }

Here while updating, in text-boxes I am getting the values present in the database where I need to get the modified values. How do I get the modified values instead?

Upvotes: 2

Views: 17401

Answers (1)

Win
Win

Reputation: 62260

Page load event fire first before firing Click event of btnSave. Using IsPostBack eliminate that problem.

protected void Page_Load(object sender, EventArgs e)
{
   if (!IsPostBack)
   {
     Info();
   }
}

Upvotes: 3

Related Questions