Accessing dynamically created textboxes text

2020-04-17 04:35发布

问题:

I have stumbled across a problem with my asp.net form.

Within my form the end user chooses a number of textboxes to be dynamically created, this all works fine with the following code:

protected void txtAmountSubmit_Click(object sender, EventArgs e)
    {
        int amountOfTasks;
        int.TryParse(txtAmountOfTasks.Text, out amountOfTasks);
        for (int i = 0; i < amountOfTasks; i++)
        {
            TextBox txtAddItem = new TextBox();
            txtAddItem.ID = "txtAddItem" + i;
            txtAddItem.TextMode = TextBoxMode.MultiLine;
            questionNine.Controls.Add(txtAddItem);
            txtList.Add(txtAddItem.ID);
        }
    }

However this has also caused a small problem for me, later on in my form on the submit button click, I send the results to the specified person it needs to go to (using smtp email). Again this part is fine, until I am trying to retrieve the text from these dynamically created textboxes.

What I have tried

  1. I have tried using this msdn access server controls ID method however this was not working.

  2. I tried to add these new textboxes to a list, however I was unsure on how to update these textboxes when they have text in them. Therefore my results were returning null because of this.

  3. I have also looked at other questions on SO such as this however they are usually for WPF or winforms, rather than my problem with asp.net (this usually isn't an issue, but I don't need to get the text from every textbox control in my page, just the ones that were dynamically created).

I have also tried changing how I call the code that I hoped would have worked:

string textboxesText = string.Join("\n", txtList.Select(x => x).ToArray());

and then in my concatenated string (email body) I would call:

textboxesText

The problem

As they are dynamically created I am finding it difficult to call them by their id for example: txtExampleID.Text, also as I have to increment the ID's by one each time (so they don't override each other) it has made things a little bit more difficult for me.

I am not asking for a code solution, I would prefer pointers in the right direction as I am still learning.

So to sum it all up: I need to get the text from my dynamically created textboxes to add it to my email body.

回答1:

The issue is these text boxes need recreated in the Load event of the page, every single time, so that both events and values can be hooked back up and retrieved.

I think the most straight forward approach, in your case, would be to extend idea #1 that you had already tried. Build a List of these controls with enough information to recreate them in Load, but you need to store that List in either ViewState or Session.

ViewState["DynamicControls"] = list;

or

Session["DynamicControls"] = list;

I would use ViewState if you can because it gets destroyed when the user leaves the page.