Asp: array of text fields

how to do something like this with asp.net <asp:textbox>

and c #? (This creates an array of text fields)

HTML:

<input name="Search[]" value="google" />
<input name="Search[]" value="yahoo" />
<input name="Search[]" value="alltheweb" />

      

PHP:

$array = $_GET['Search']; // or $_POST['Search'];

/*
$array is now an array like:
array(
0 => "google",
1 => "yahoo".
2 => "alltheweb"
)
/*

      

+2


source to share


2 answers


Since all of the controls will be heavily numbered it would be easy to just grab them by name, but if you need them in an array, you can wrap the controls in the panel.

You can do something similar to this:

<div runat="server" id="myPanel">
    <asp:TextBox runat="server" id="search1" />
    <asp:TextBox runat="server" id="search2" />
    <asp:TextBox runat="server" id="search3" />
</div>

      

Linq:

IEnumerable<string> values = myPanel.Controls.OfType<TextBox>()
                                             .Select(textBox => textBox.Text);

      

Non Linq:

string[] values = new string[myPanel.Controls.Count];
for(int i = 0; i < myPanel.Controls.Count; ++i)
{
    values[i] = (myPanel.Controls[i] as TextBox).Text;
}

      

Edited:



If you are going to add (or just have non-asp) inputs dynamically, then it is actually much easier to include inputs to the array server.

For example, if you want to have a binding <input type='text' name='search[]' />

on a page, on the server you can do the following to include the elements in a string array:

string[] inputValues = Request.Form["search[]"].Split(',');

      

So, for the original example, assuming the equivalent would be:

HTML:

<input name="Search[]" value="google" />
<input name="Search[]" value="yahoo" />
<input name="Search[]" value="alltheweb" />

      

FROM#:

string[] myArray = Request.Form["search[]"].Split(',');

/*
myArray  is now an array like:
0: "google"
1: "yahoo"
2: "alltheweb"
/*

      

+4


source


You can also create an array like this:

TextBox[] textBoxes = new[] { search1, search2, search3 };

<div runat="server" id="myPanel">
    <asp:TextBox runat="server" id="search1" />
    <asp:TextBox runat="server" id="search2" />
    <asp:TextBox runat="server" id="search3" />
</div>

      



It gives the same end result as Quintin's answer, but it's easier for me to read.

0


source







All Articles