Connor Mackay
Connor Mackay

Reputation: 77

How to retrieve data from dynamically created textboxes and build strings

So I have some code, that creates a row of 4 textboxes. The data from those 4 textboxes will be combined to make a SQL query and then executed. The button to add a row can be hit an infinite amount of times. I have my IDs generated so that on the first click textbox one is txtBox1Row1, then on the second click it is txtBox1Row2 etc, etc.

Now I need a way to retrieve the data from each row and build SQL queries from them. Just to reiterate, I only need the data from the 4 textboxes in each row per loop (I assume thats how this will need to be done).

So how do I go about doing this?

Thanks a lot, the help is always appreciated. I was planning on doing it like this:

        foreach (Control c in pnlArea.Controls)
        {
            if (c.ID.Contains("ddlArea"))
            {
                area.Add(((DropDownList)c).SelectedValue);
            }
            if (c.ID.Contains("txtArea"))
            {
                areaOther.Add(((TextBox)c).Text);
            }
            if (c.ID.Contains("ddHazard"))
            {
                hazard.Add(((DropDownList)c).SelectedValue);
            }
            if (c.ID.Contains("txtHazard"))
            {
                hazardOther.Add(((TextBox)c).Text);
            }
            if (c.ID.Contains("txtHazardDesc"))
            {
                hazardDesc.Add(((TextBox)c).Text);
            }
            if (c.ID.Contains("txtActionDesc"))
            {
                actionDesc.Add(((TextBox)c).Text);
            }
            if (c.ID.Contains("calDueDate"))
            {
                dueDate.Add(((Calendar)c).SelectedDate);
            }
        }

Upvotes: 0

Views: 49

Answers (1)

Ryan Gibbs
Ryan Gibbs

Reputation: 1310

Per Nkosi, you'd want to encapsulate your textbox 'area' in a form.

What I would recommend is looping through each textbox in the form and storing in a dictionary.

Here's what that might look like:

Dictionary<string, string> textBoxVals = new Dictionary<string, string>();

Control form = this.FindControl("form1") as Control;

TextBox tb;

foreach (Control c in form.Controls)
{
    if (c.GetType() == typeof(TextBox))
    {
        tb = c as TextBox;
        textBoxVals.Add(tb.ID, tb.Text);
    }
}

Then you'd be able to loop through the dictionary to build your SQL string. The dictionary would contain both the dynamic name of the control and the value of the textbox.

Based on the code you posted it looks like maybe there are some other controls that might also be associated with each line. If that's the case, you can create another if statement in the foreach loop to handle different control types, so that you're saving the proper parameters of them.

I hope that helps.

Upvotes: 2

Related Questions