如何命名和查找动态创建的webcontrols在c# [英] How to name and find dynamically created webcontrols in c#

查看:121
本文介绍了如何命名和查找动态创建的webcontrols在c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我尝试过:

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

生成的html包括我的名称和自动生成的名称作为文本框的属性。



不幸的是,当我运行一个 FindControl ,按我的名字,我得到一个空引用,尽管它仍然可以找到它由自动生成的名称。



我需要做什么来找到我的名字控制?何时/为什么自动生成我的控件的名称?



成功代码:

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



不成功的代码:

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

解决方案

这取决于什么版本的ASP.Net。从历史上看,您无法控制Id和控件的名称。在ASP.Net 4.0中,这改变了。您可以控制Id的呈现方式。为什么不使用此功能?



以下是关于.Net 4.0中新增功能的文章: http://www.dotnetfunda.com/articles/article893-control-over-client-ids- aspnet-40-.aspx



有没有理由指定name属性?



如果您使用的是旧版本(3.5),这不是那么容易。 FindControl仅查找控件的ID,而不是名称。


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

解决方案

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.

这篇关于如何命名和查找动态创建的webcontrols在c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆