How to name and find dynamically created webcontrols in c#

scott picture scott · Aug 11, 2010 · Viewed 9k times · Source

I am trying to add a unique name to each textbox that I'm adding to a table.

I've tried:

TableRow someRow = new TableRow();
TableCell someCell = new TableCell();
TextBox someTextbox = new TextBox();

someTextbox.Attributes.Remove("name");
someTextbox.Attributes.Add("name",itsId);

someCell.Controls.Add(someTextBox);
someRow.Cells.Add(someCell);
theTable.Rows.Add(someRow);

The html generated includes both my name and the autogenerated name as attributes of the textbox.

Unfortunately, when I run a FindControl, by my name, I get a null reference, even though it still works to find it by the autogenerated name.

What do I need to do to find the control by my name? When / why is it autogenerating names for my controls?

Successful code:

TextBox tb = (TextBox)FindControl(autogeneratedID);
WriteToSomeOtherDiv(tb.Text);

Unsuccessful code:

TextBox tb = (TextBox)FindControl(myId);
WriteToSomeOtherDiv(tb.Text);

Answer

Chuck Conway picture Chuck Conway · Aug 11, 2010

It depends on what version of ASP.Net. Historically you did not have control over the Id's and the names of the controls. In ASP.Net 4.0, this changed. You can control how the Id's are rendered. Why not use this feature instead?

Here is an article on the new feature in .Net 4.0 : http://www.dotnetfunda.com/articles/article893-control-over-client-ids--aspnet-40-.aspx

Is there a reason you are targeting the name attribute?

If you are using an older version (3.5) this isn't so easy. The FindControl only looks for the id of the control, not the name.