1

Is there a way to add additional textboxes to an aspx based on entries from an xml file?

Ie. An xml file reads

<Number>
  <Num>1</Num>
  <Num>2</Num>
  <Num>3</Num>
</Number>

And I want to insert a new textbox every time Num = 2. Also, I'm working in C# in Visual Studio if that helps.

2
  • Create model class for the XML and read(deserialize) the xml into class object. Loop through the NUM list and if you find a 2, add textbox control on the page. Commented May 19, 2017 at 19:52
  • Can you show what you're trying to add it to? Also, Webforms, right? Commented May 19, 2017 at 20:30

1 Answer 1

0

It's actually fairly straightforward. First, add something like the following to your aspx:

<div id="divToAddTo" runat="server" />

This doesn't strictly have to be a div - just whatever you want to add controls to.

In your code-behind, do something like this:

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 = true
    };
    divToAddTo.Controls.Add(box);

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

    i++;
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks EJoshuaS. How would you get the text entered into the different textboxes though?
@BlahBlah You can add an ID dynamically when you create the ID (shown in my edit)
EJoshuaS, I added the ID dynamically like you put but when trying to call it in other parts of the same file to retrieve the text entered in the textbox, it says that dynamicTextBox1 does not exist. Do you know why and a way to fix this?
@BlahBlah Since it's created at runtime, it won't exist at compile-time. If you're looking for it from jQuery or JavaScript it won't be a problem because it's guaranteed to exist by the time that the page is rendered, but you can actually find it dynamically if you're looking for it in code-behind (either by looking in the control or keeping a separate list of the Text Boxes).
EJoshuaS the only problem with keeping a separate list of the text boxes is that it does have the box IDs but not any of the information that the user enters into the text box after the text box has been added to the list

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.