How to name and find dynamically created webcontrols in c#

微笑、不失礼 提交于 2019-12-08 08:46:58

问题


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:


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.




回答2:


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


来源:https://stackoverflow.com/questions/3453989/how-to-name-and-find-dynamically-created-webcontrols-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!