I'm having a problem with a dynamic LinkButton.
For a result returned from a database query, I create two LinkButtons, dynamically. One is "Update" and the other is "Delete".
I store Update or Delete in the .CommandName property. I store the identity value (the primary key) of the database record in the .CommandArgument property.
All of this is in a method that is called when a user clicks a particular record displayed from a previous operation. Still with me?
public void createUpDelPaper(int xPaperID, string xPaperTitle)
{
PlaceHolder1.Controls.Add(new LiteralControl("<fieldset>"));
PlaceHolder1.Controls.Add(new LiteralControl("<legend>Update/Delete Paper</legend>"));
PlaceHolder1.Controls.Add(new LiteralControl("<label for='title'>Title:</label>"));
txtNewPaper = new TextBox();
txtNewPaper.Columns = 45;
txtNewPaper.ID = "title";
txtNewPaper.CssClass = "input-box";
txtNewPaper.Text = xPaperTitle;
txtNewPaper.TextMode = System.Web.UI.WebControls.TextBoxMode.SingleLine;
txtNewPaper.Attributes.Add("onkeypress","enterSubmit(this,event)");
PlaceHolder1.Controls.Add(txtNewPaper);
lnkAddPaper = new LinkButton();
lnkAddPaper.CommandName = "UpdatePaper";
lnkAddPaper.CssClass = "submit-button";
lnkAddPaper.Text = "Update";
lnkAddPaper.ID = "Update";
lnkAddPaper.Command += new System.Web.UI.WebControls.CommandEventHandler(paperTitle_Click);
PlaceHolder1.Controls.Add(lnkAddPaper);
lnkAddPaper = new LinkButton();
lnkAddPaper.CommandName = "DeletePaper";
lnkAddPaper.CssClass = "submit-button";
lnkAddPaper.Text = "Delete";
lnkAddPaper.ID = "Delete";
lnkAddPaper.Command += new System.Web.UI.WebControls.CommandEventHandler(paperTitle_Click);
PlaceHolder1.Controls.Add(lnkAddPaper);
PlaceHolder1.Controls.Add(new LiteralControl("</fieldset>"));
ViewState.Add("ManagePapers","2");
}
Now, I do know about dynamic controls. The next time the page loads, these controls have to be recreated, and then the ViewState mechanism ties these "new" controls to their delegates for event processing.
All well and good. But when I recreate these controls, I cannot recreate the .CommandArgument. It's a chicken-and-egg thing. I store the primary key value in the .CommandArgument so that I know which record to update or delete. But the value of .CommandArgument is set conditionally, and that condition doesn't exist on PostBack.
How can I make the value persist?
One answer: don't store it in .CommandArgument, put it in a ViewState variable.
But this process has revealed a gap in my knowledge in how to deal with dynamically created controls. Any insights?