| | |
ASP.NET / C# Dynamic Control
Please support our ASP.NET advertiser: Intel Parallel Studio Home
![]() |
•
•
Join Date: Dec 2004
Posts: 1,655
Reputation:
Solved Threads: 35
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?
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?
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?
ASP.NET Syntax (Toggle Plain Text)
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?
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?
•
•
Join Date: Dec 2004
Posts: 1,655
Reputation:
Solved Threads: 35
•
•
•
•
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 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.
•
•
Join Date: Dec 2004
Posts: 1,655
Reputation:
Solved Threads: 35
This little problem made me delve deeply into the issues. The results of my investigation:
http://www.tgreer.com/aspnet_html_04.html
http://www.tgreer.com/aspnet_html_04.html
•
•
Join Date: May 2005
Posts: 1
Reputation:
Solved Threads: 0
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.
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.
ASP.NET Syntax (Toggle Plain Text)
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); } } }
![]() |
Similar Threads
- Simple ASP.Net Login Page using C# (C#)
- ASP.Net timer control (ASP.NET)
- How To Hyperlink Normal HTML page with ASP.NET Page? (ASP.NET)
- ASP.NET Timer Button (ASP.NET)
- ASP in ASP.NET application (ASP.NET)
Other Threads in the ASP.NET Forum
- Previous Thread: Calling function to add HTML to the page
- Next Thread: only functions when focused in the first column
| Thread Tools | Search this Thread |
.net 2.0 3.5 ajax alltypeofvideos appliances asp asp.net beginner box browser businesslogiclayer button c# cac checkbox class commonfunctions compatible content contenttype countryselector courier dataaccesslayer database datagrid datagridview datalist deployment development dgv dialog dropdownlist dropdownmenu dynamic dynamically edit embeddingactivexcontrol fileuploader fill findcontrol flash flv formatdecimal formview gridview gudi iis javascript list listbox menu microsoft mouse mssql nameisnotdeclared news novell numerical opera order panelmasterpagebuttoncontrols problem radio ratings redirect registration relationaldatabases reportemail schoolproject search security serializesmo.table sessionvariables silverlight smoobjects software sql sql-server sqlserver2005 ssl tracking treeview unauthorized validatedate validation vb.net videos vista visual-studio visualstudio vs2008 web webapplications webarchitecture webdevelopment webprogramming webservice xsl youareanotmemberofthedebuggerusers






