User Name Password Register
DaniWeb IT Discussion Community
All
What is DaniWeb IT Discussion Community?
You're currently browsing the ASP.NET section within the Web Development category of DaniWeb, a massive community of 426,445 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 2,160 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our ASP.NET advertiser: Lunarpages ASP Web Hosting
Views: 58030 | Replies: 4
Reply
Join Date: Dec 2004
Posts: 1,590
Reputation: tgreer is an unknown quantity at this point 
Rep Power: 7
Solved Threads: 35
Colleague
tgreer tgreer is offline Offline
Made Her Cry

ASP.NET / C# Dynamic Control

  #1  
Mar 30th, 2005
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?
AddThis Social Bookmark Button
Reply With Quote  
Join Date: Feb 2003
Location: Canada
Posts: 786
Reputation: Paladine has a spectacular aura about Paladine has a spectacular aura about Paladine has a spectacular aura about 
Rep Power: 9
Solved Threads: 25
Colleague
Paladine's Avatar
Paladine Paladine is offline Offline
Master Poster

Re: ASP.NET / C# Dynamic Control

  #2  
Apr 4th, 2005
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?
Assistant Manager, Regional Pharmacy Information Systems
TLC Services Website (Under Construction)
Updated : ASP.Net Login Code
Reply With Quote  
Join Date: Dec 2004
Posts: 1,590
Reputation: tgreer is an unknown quantity at this point 
Rep Power: 7
Solved Threads: 35
Colleague
tgreer tgreer is offline Offline
Made Her Cry

Re: ASP.NET / C# Dynamic Control

  #3  
Apr 4th, 2005
Originally Posted by Paladine
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.
Reply With Quote  
Join Date: Dec 2004
Posts: 1,590
Reputation: tgreer is an unknown quantity at this point 
Rep Power: 7
Solved Threads: 35
Colleague
tgreer tgreer is offline Offline
Made Her Cry

Re: ASP.NET / C# Dynamic Control

  #4  
Apr 8th, 2005
This little problem made me delve deeply into the issues. The results of my investigation:

http://www.tgreer.com/aspnet_html_04.html
Reply With Quote  
Join Date: May 2005
Posts: 1
Reputation: sam_dlg is an unknown quantity at this point 
Rep Power: 0
Solved Threads: 0
sam_dlg sam_dlg is offline Offline
Newbie Poster

Re: ASP.NET / C# Dynamic Control

  #5  
May 18th, 2005
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);
      }
	}
}
Reply With Quote  
Reply

Only community members can participate in forum threads. You must register or log in to contribute.

DaniWeb ASP.NET Marketplace
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)

 

Thread Tools Display Modes

Similar Threads
Other Threads in the ASP.NET Forum

All times are GMT -4. The time now is 2:58 pm.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC