posts - 50,  comments - 1445,  trackbacks - 17

When reading data from a database using the Page_Load event and then updating the database, the data doesn't get updated as described here.

By including

if (!Page.IsPostback)

in before the reader allows data to be updated in other areas on the page/form. Below are examples:

Update doesn't work:
==================================================================

protected void Page_Load(object sender, EventArgs e)
{
      DataList1.DataBind(); 
}

protected void DataList1_UpdateCommand(object source, DataListCommandEventArgs e)
{
      SqlConnection sqlConn = new SqlConnection("connection");
      SqlCommand sqlComm = new SqlCommand("UPDATE blog_Postings SET title = @title, body = @body WHERE (id = @id)", sqlConn);

      sqlComm.Parameters.Add(new SqlParameter("@id", SqlDbType.Int));
      sqlComm.Parameters["@id"].Value = intID;
      sqlComm.Parameters.Add(new SqlParameter("@title", SqlDbType.NVarChar));
      sqlComm.Parameters["@title"].Value = strTitle;
      sqlComm.Parameters.Add(new SqlParameter("@body", SqlDbType.NVarChar));
      sqlComm.Parameters["@body"].Value = strBody;

      sqlComm.CommandType = CommandType.StoredProcedure; 

      sqlConn.Open();
      sqlComm.ExecuteNonQuery();
      sqlConn.Close();
      sqlComm.Dispose();

      DataList1.EditItemIndex = -1;
      DataList1.DataBind();
}

When the DataList is updating, the function protected void Page_Load(object sender, EventArgs e) runs again/refreshes which retrieves the old values in the database.


Update works:
==================================================================

protected void Page_Load(object sender, EventArgs e)
{
      if (!Page.IsPostBack)
      {
            DataList1.DataBind();
      } 
}

protected void DataList1_UpdateCommand(object source, DataListCommandEventArgs e)
{
      SqlConnection sqlConn = new SqlConnection("connection");
      SqlCommand sqlComm = new SqlCommand("UPDATE blog_Postings SET title = @title, body = @body WHERE (id = @id)", sqlConn);

      sqlComm.Parameters.Add(new SqlParameter("@id", SqlDbType.Int));
      sqlComm.Parameters["@id"].Value = intID;
      sqlComm.Parameters.Add(new SqlParameter("@title", SqlDbType.NVarChar));
      sqlComm.Parameters["@title"].Value = strTitle;
      sqlComm.Parameters.Add(new SqlParameter("@body", SqlDbType.NVarChar));
      sqlComm.Parameters["@body"].Value = strBody;

      sqlConn.Open();
      sqlComm.ExecuteNonQuery();
      sqlConn.Close();
      sqlComm.Dispose(); 

      DataList1.EditItemIndex = -1;
      DataList1.DataBind();
}

So, as you can see by not validating the postback will causes data not to update which will lead into hours of frustration. Enjoy...

(Posted using Windows Live Writer)

posted on Tuesday, October 17, 2006 5:01 PM

Post a new comment about this topic
Title  
Name  
Url

Comments   
Protected by Clearscreen.SharpHIPEnter the code you see: