I want to add a control to a placeholder dynamically, like this:
int fileCount = Convert.ToInt32(lblCount.Text);
for (int i = 0; i<fileCount ; i++)
{
FileUpload fu = new FileUpload();
if(PlaceHolder1.HasControls())
PlaceHolder1.Controls.AddAt(i,fu);
else
PlaceHolder1.Controls.Add(fu);
PlaceHolder1.Controls[i].ID = "123456abcdef" + i;
}
But I get the error
Multiple controls with the same ID ‘123456abcdef0’ were found. FindControl requires that controls have unique IDs.
Why? Only one control should get that ID on each iteration of the loop.
EDIT: Should mention that I haven’t actually been able to test the loop, I get the error even when fileCount is 1.
SOLUTION: I called this function from a “foreach” loop in page load when I thought it was outside of it. Still, having the clear() method in mind will remove the necessity of the addat part of the function.
Just do a clear before you start adding:
And your add statements can be simplified as follows: