Using C#, how can I read the content of dynamic created textboxes?

眉间皱痕 提交于 2019-12-24 00:44:01

问题


Hy,

I have created some dynamic textboxes with standard content.

Does anyone know how can I read the content of these textboxes (assuming that user modified the standard content) when I press one button?

Thanks a lot.

Jeff

Update

This is how I am creating the textboxes:

foreach (string name in listOfNames)
{
   TextBox tb = new TextBox();
   tb.Text = name;
   tb.BorderStyle = BorderStyle.None;
   tb.BorderWidth = 0;
   tb.Font.Name = "Arial";
   tb.Font.Size = 8;
}

回答1:


The specific will vary depending on the technology you are using. However the concept would remain very similar, though for ASP.NET it will be a little more interesting.

WinForms/WPF/Silverlight

Maintain a list of the dynamically created textboxes and when the button is pressed you can run through the list of textboxes and read the Text property to get the user input.

ASP.NET - After the tag update it seems this section is most appropriate to your requirement.

For ASP.NET you will need to create the textboxes in an override of the OnInit method, this should happen on each postback. Then in the Button.Click event you can read the user input from the textboxes that you created in the OnInit function. You need to ensure that the controls are created with the same ID on each post back.




回答2:


You need to ensure that the text boxes are recreated on every postback.

If you do not recreate them, you will not be able to access their properties or events.

The best place to create dynamic controls is the page Init event handler.

I suggest reading up on the ASP.NET page life cycle.


Update (following updated question)

Make sure to set an ID (and a different one, at that) for the text boxes, so you can refer to them later on.

I can't see where you are adding these controls to the page either.




回答3:


Request.Form is a collection of Key-Value pairs that represents all of the data coming back from the ASP.NET request. If you access that you can get any value whether its control is specified in the ASPX code or dynamically created in the code behind file.

You can also get their values placed back in them automatically if you recreate them during the init part of the page lifecycle. If you do this, their values will be set when ASP.NET recreates the state of the page and applies the values from the form.




回答4:


You should be able to access them as you would a normal control, you just need to get a reference to the control. Remember to re-create all controls on each postback.

this is a useful article on dynamic controls in asp.net



来源:https://stackoverflow.com/questions/4499934/using-c-how-can-i-read-the-content-of-dynamic-created-textboxes

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