Question

I have an asp placeholder in my page, and I dynamically insert "rows" into it, where each row is a user control.

If the request is a GET request, I load the data from the database and populate as many user controls as needed. I also add the control instances into the session contents.

If the request is a POST request, I first re-create the controls by looking at the session contents, inside of Page_Load(). Afterwards, each button's handler can do whatever extra work it needs to be done, such as add a new row (to the placeholder, the session, and the DB), delete a row (from placeholder, session, and DB), or update an existing row.

I am facing several issues here:

  1. When deleting rows, sometimes the wrong data is displayed on the screen after the delete, even though the right row was deleted. This is dangerous, because for further deletes we don't know which rows will be affected.
  2. When adding a new row, sometimes one of the existing rows will have the wrong data in it (specifically data from another existing row)

How can I fix these issues? I am having a hard time even diagnosing the problem. Are these common issues? Am I just doing this completely wrong? What are better ways to accomplish this?

Was it helpful?

Solution

I've had issues like this before. I fixed them by:

  • When you instantiate your usercontrol before you put it into the placeholder it needs to have the same ID as it did before postback (ie when you first created it). I do something like "usr_" + <db record id>. This ensures its the same ID no matter what order it gets loaded, what records get deleted, etc. This is probably the most important thing to do, because if you don't assign it ID's .NET will assign them for you -- and they are assigned in the order they show up in the control collection which means you potentially will have the wrong info in the wrong user control (which you described in your question).
  • Not using the session to store info about the page. Once the ID issues were fixed people were still having issues if the opened up two tabs of the same page.

Something along these lines:

using (SqlConnection c = new SqlConnection(DB_STRING))
{
    c.Open();
    String sql = @"
        SELECT *
        FROM yourTable
        ORDER BY ID;";
    using (SqlCommand cmd = new SqlCommand(sql, c))
    {
        using (SqlDataReader d = cmd.ExecuteReader())
        {
            while (d.Read())
            {
                UserControl uc = (UserControl)new UserControl().LoadControl("~/path/to-your-control/YourControl.ascx");
                uc.ID = "usr_" + d["ID"];
                plcHolderRows.Controls.Add(uc);
            }
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top