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:
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?
I've had issues like this before. I fixed them by:
"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).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);
}
}
}
}