Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to retrieve values from 100 Textboxes using loop

Tags:

.net

asp.net

Friends,

I Have a grid of 100 or more text boxes (HTML OR ASP.NET) each will be containing a text value of fixed length, need ALL of these passed back to the back end form for mass updating of the database..

I can do this by simple going through each of the controls .text property in code behind.

However that makes the code to big and ugly.

I was wondering if there is any why to go through each control using some controlled looping structure and retrieve data

i.e.

Private List<string> getdata()
{
  Private List<String> MyList = new List<string>();
    foreach (Textbox)control txbControl in ....// don't know what this will be
     {
       MyList.Add(txbControl.text);
     }
}

Please note that all of these textboxes have unique ID tag on the page i.e.

<tablr>
<tbody>
<tr>
<td>
<asp:TextBox ID="TxB_Customize1" runat="server"></asp:TextBox>
<td/>
<td>
<asp:TextBox ID="TxB_Customize2" runat="server"></asp:TextBox>
<td/>
<td>
<asp:TextBox ID="TxB_Customize3" runat="server"></asp:TextBox>

... ... ...

Sorry forgot to mention this, text boxes are grouped in columns and each textbox in a given column shares similar name i.e. "Txb_Customize" in the given instance.

So when retrieving the values I also need to know from where its coming from (may be textbox ID).

like image 600
h_power11 Avatar asked Jul 16 '26 00:07

h_power11


1 Answers

Look at the Control.Controls property.

You'd want something like:

foreach (Control control in Controls)
{
    TextBox textBox = control as TextBox;
    // Ignore non-textboxes
    if (textBox != null)
    {
        list.Add(textBox.Text);
    }
}

If you're using .NET 3.5 you could do this in a simpler way with LINQ:

return Controls.OfType<TextBox>()
               .Select(textBox => textBox.Text)
               .ToList();
like image 189
Jon Skeet Avatar answered Jul 18 '26 15:07

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!