by Tim
7. October 2011 09:14
Looping through a particular set of server controls is quite straight forward, especially if you use group naming conventions.
For example, I have three file upload controls on my page that I want to loop through. I assign the ID names as follows:
pictureFileUpload1
pictureFileUpload2
pictureFileUpload3
In order to loop through these controls in the code, I use:
protected void Button1_Click(object sender, EventArgs e)
{
for (int i=1; i < Page.Form.Controls.Count; i++)
{
if (Page.Form.Controls[i].UniqueID.ToString().Contains("picture"))
{
FileUpload currFileUpload = Page.Form.Controls[i] as FileUpload;
if (currFileUpload.HasFile)
{
Label1.Text += currFileUpload.ID + " has file!";
}
}
}
}
The code is self-explanatory, though there are some notable points:
- Each server control in the page is looped through to begin with.
- The UniqueID must be used - if ID is used an error will be thrown
Try running the following script on page load to understand why UniqueID and not ID must be used. Run the script first with ID and then change it to UniqueID:
foreach (Control ctrl in Page.Form.Controls)
{
Label1.Text += ctrl.ID + "
";
}
UniqueID differs from the ID property, in that the UniqueID property includes the identifier for the server control's naming container. This identifier is generated automatically when a page request is processed.
http://msdn.microsoft.com/en-us/library/system.web.ui.control.uniqueid.aspx