views:

102

answers:

2

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);

+1  A: 

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.

Chuck Conway
when I instead set the id by using attributes.add("id",itsId), it did not work.However, setting someTextBox.ID = itsId does work, and in the generated html the "name" attributes gets the same value as the name.
scott
A: 

Looks like you need to place your controls on a placeholder and find that control on the placeholder rather than the form. Please see example below on removing and adding custom controls and dynamic controls where you need to find the control first before you can interact with it. For a full explanation I have it in my blog --> http://anyrest.wordpress.com/2010/04/06/dynamically-removing-controls-in-a-parent-page-from-a-child-control/. Let me know if this solved your issue.

public UserControl myCustomControl = new UserControl();
public Button myDynamicButton = new Button();

protected void btnAddControl_Click(object sender, EventArgs e)
{
    myCustomControl = (UserControl)Page.LoadControl("SampleControlToLoad.ascx");
    PlaceHolder myPlaceHolder = (PlaceHolder)Page.FindControl("PlaceHolder1");

    myPlaceHolder.Controls.Add(myCustomControl);
}
protected void btnRemoveControl_Click(object sender, EventArgs e)
{
    PlaceHolder myPlaceHolder = (PlaceHolder)Page.FindControl("PlaceHolder1");
    if (myPlaceHolder.Controls.Contains(myCustomControl))
    {
        myPlaceHolder.Controls.Remove(myCustomControl);
        myDynamicButton.Dispose();
    }
}
Raymund