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?

Dani AI

Generated

Short answer: CommandArgument will only be restored if the control is re-created with the same ID early in the page lifecycle (before ViewState is applied). The symptom you saw — CommandArgument missing or extra controls appearing — comes from creating controls conditionally at the wrong time (or not recording the fact they need to be re-created on postback).

Pattern to follow

  • Record the minimal page-state that tells you which dynamic controls to render (a comma list, array, or ViewState entry of IDs). Do this when you first create the controls.
  • Re-create those controls on every request in OnInit (Page_Init) using stable IDs, set CommandArgument at creation, and wire the Command handler there. That guarantees ASP.NET can restore ViewState and route the Command event correctly.

Small example (concept only)

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    var idsCsv = (string)ViewState["PaperIDs"];
    if (!string.IsNullOrEmpty(idsCsv))
    {
        foreach (var id in idsCsv.Split(','))
        {
            var lnk = new LinkButton();
            lnk.ID = "lnkUpdate_" + id;
            lnk.CommandName = "UpdatePaper";
            lnk.CommandArgument = id;
            lnk.Command += new CommandEventHandler(paperTitle_Click);
            PlaceHolder1.Controls.Add(lnk);
        }
    }
}

Notes, alternatives and pitfalls

  • suggested Session — it works but is heavier than page-scoped ViewState or a HiddenField. Use Session only when you need cross-page/session persistence.
  • ’s duplicate-textbox issue is exactly why re-creating controls in LoadViewState or after ViewState is applied produces glitches; do it in OnInit.
  • If you can use a data-bound control (Repeater/GridView) with DataKeyNames, ASP.NET handles IDs and arguments for you and avoids manual recreation.
  • Always keep IDs deterministic and wire event handlers every time you create the control.

Quick checklist

  • Save which IDs to render (ViewState/hidden field) when adding controls.
  • Recreate controls in OnInit with the same IDs.
  • Set CommandArgument at creation and attach the handler.
  • Consider data-bound controls or hidden fields if the pattern gets complex.

(See ’s thread for the original scenario and experimentation.)

Recommended Answers

All 5 Replies

It is late and I am a little tired so reading code is getting hard at this hour.... but why not store this variable value in a Session variable?

It is late and I am a little tired so reading code is getting hard at this hour.... but why not store this variable value in a Session variable?

The ViewState mechanism is much better, for my purposes. I don't need the value to persist through the entire Session.

The real question is, why doesn't it persist through the Viewstate automatically?

If you create a dynamic textbox, conditionally, say in response to some other control's click event. Then, on PostBack, you recreate a "new" TextBox with the same object name, then "magically" that new textbox becomes the dynamically-created textbox. You get all of the user-initiated and code-generated properties.

What I've discovered is that, at least with ListButtons, is that the CommandArgument property doesn't act this way.

i'm doing the following and when i click the button to submit it ends up adding an additional textbox.

I have a calculator where you can dynamically add controls. And I'm able to add new textboxes for additional numbers and on that same page I have a "sum values" button that does just that. The problem is that when I do a sum value it pulls the view state again and creates a new textbox. That's because for some reason my viewstate is updated after the page is created.

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace DynamicControlLoading
{
	/// <summary>
	/// Summary description for WebForm1.
	/// </summary>
	public class WebForm1 : System.Web.UI.Page
	{
      protected System.Web.UI.WebControls.Button Button1;
      protected System.Web.UI.WebControls.Panel Panel1;
      protected System.Web.UI.WebControls.Button Button2;
   
      public Int32 Count
      {
         get 
         {
            if (ViewState["count"] == null)
               ViewState["count"] = 0;
            return Int32.Parse(ViewState["count"].ToString());
         }
         set
         {
            ViewState["count"] = value;
         } 
      }
		private void Page_Load(object sender, System.EventArgs e)
		{
         if (IsPostBack)
         {
            if (ViewState["mode"].ToString() == "1")
               Response.Write("clicked");
         }
         else
         {
            ViewState.Add("mode", "0");
            Count = 0;
         }
		}

		#region Web Form Designer generated code
      
      override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
         this.Button1.Click += new System.EventHandler(this.Button1_Click);
         this.Button2.Click += new System.EventHandler(this.Button2_Click);
         this.Load += new System.EventHandler(this.Page_Load);
      }

      protected override void LoadViewState(object savedState)
      {
         base.LoadViewState(savedState);
         if (ViewState["mode"].ToString() == "1")
            AddTextBox();
      }
		#endregion

      private void Button2_Click(object sender, System.EventArgs e)
      {
         Count += 1;
         AddTextBox();
         ViewState.Add("mode", "1");
      }

      private void AddTextBox()
      {
         for (int i = 1; i <= Count; i++)
         {
            TextBox txtBox = new TextBox();
            txtBox.ID = String.Format(
               "txtBox{0}", i);
            Panel1.Controls.Add(txtBox);
         }
      }

      private void Button1_Click(object sender, System.EventArgs e)
      {
         int grandTotal = 0;
         /*
          * for (int i = 1; i <= Count; i++)
         {
            grandTotal += int.Parse(Request.Form[
                              String.Format("txtBox{0}", i)]);
         }
         */
         for (int i = 1; i <= Count-1; i++)
         {
            TextBox txt = (TextBox) Panel1.FindControl(
               String.Format("txtBox{0}", i));

            grandTotal += int.Parse(txt.Text.ToString());
         }
         Response.Write(grandTotal);
      }
	}
}

use <a href> with Eval() function instead of commandargument.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.