0

In this post I wanted to figure out how to create dynamically created textboxes in C# Visual Studio.

Adding additional textboxes to aspx based on xml

However, when I try to call the ID of these dynamically created textboxes later in my code to figure out what text the user entered into them, I am getting an error that says these IDs do not exist in the current context. Does anyone know how I would be able to call these?

3
  • Make sure you recreate dynamic controls on every postback. Commented May 24, 2017 at 16:57
  • @VDWWD what do you mean by this? Can you give an example? Commented May 24, 2017 at 18:05
  • aspsnippets.com/Articles/… Commented May 24, 2017 at 18:08

2 Answers 2

1

credit to Adding additional textboxes to aspx based on xml

Here is my entire code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;

namespace WebApplication4
{
    public partial class WebForm15 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsCallback)
            {
                //credit to https://stackoverflow.com/questions/44076955/adding-additional-textboxes-to-aspx-based-on-xml#comment75336978_44078684
                const string xml = @"<Number>
                       <Num>1</Num>
                       <Num>2</Num>
                       <Num>3</Num>
                     </Number>";

                XDocument doc = XDocument.Parse(xml);
                int i = 0;

                foreach (XElement num in doc.Root.Elements())
                {
                    TextBox box = new TextBox
                    {
                        ID = "dynamicTextBox" + i,
                        Text = num.Value,
                        ReadOnly = false
                    };
                    divToAddTo.Controls.Add(box);

                    divToAddTo.Controls.Add(new LiteralControl("<br/>"));

                    i++;
                }
            }
        }

        protected void BtnGetValues_Click(object sender, EventArgs e)
        {
            IList<string> valueReturnArray = new List<string>();
            foreach (Control d in divToAddTo.Controls)
            {
                if (d is TextBox)
                {
                    valueReturnArray.Add(((TextBox)d).Text);
                }
            }
            //valueReturnArray will now contain the values of all the textboxes
        }
    }
}

Here is aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm15.aspx.cs" Inherits="WebApplication4.WebForm15" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
</head>
<body>
    <form id="form1" runat="server">
        <div id="divToAddTo" runat="server" />
        <asp:Button runat="server" ID="BtnGetValues" Text="GetValues" OnClick="BtnGetValues_Click" />
    </form>
</body>
</html>
Sign up to request clarification or add additional context in comments.

3 Comments

I tried your answer here and it gives me a list of empty strings. Would you know why or how to fix this?
@Blah Blah please try my repost. Please let me know if I can help you with anything else.
kblau again it didn't work. I believe that my problem is that the user types in information and when a button is pressed to save their data a post back occurs and erases the text boxes and what was created in them. Thus, all my textboxes are empty strings. Also as a side note the textboxes are populated by the user whereas the xml determines how many textboxes are needed. If you have any other solutions it would be much appreciated
0

Figured it out!!! Here is what I found after scouring the internet for hours

Solution: When using dynamic controls, you must remember that they will exist only until the next postback.ASP.NET will not re-create a dynamically added control. If you need to re-create a control multiple times, you should perform the control creation in the PageLoad event handler ( As currently you are just creating only for first time the TextBox using Condition: !IsPostabck ). This has the additional benefit of allowing you to use view state with your dynamic control. Even though view state is normally restored before the Page.Load event, if you create a control in the handler for the PageLoad event, ASP.NET will apply any view state information that it has after the PageLoad event handler ends.

So, Remove the Condition: !IsPostback, So that each time the page Loads, The TextBox control is also created. You will also see the State of Text box saved after PageLoad handler completes. [ Obviously you have not disabled ViewState!!! ]

Example:

protected void Page_Load(object sender, EventArgs e) {

TextBox txtBox = new TextBox();
// Assign some text and an ID so you can retrieve it later. 

txtBox.ID = "newButton";
PlaceHolder1.Controls.Add(txtBox);

} Now after running it, type anything in text box and see what happens when you click any button that causes postback. The Text Box still has maintained its State!!!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.