如何从ASP.NET中动态创建的HTML控件访问值 [英] How do I access the values from dynamically created HTML controls in ASP.NET

查看:68
本文介绍了如何从ASP.NET中动态创建的HTML控件访问值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I have created few HTML controls dynamically on Page load.
My Code looks like this:

<pre>Protected Sub Page_Load(sender as Object, e As EventArgs) Handles Me.Load
      Dim sb As New StringBuilder
      Dim i as Integer = 0
      sb.Append("<table class ='tabledata' id='tblContent'>")
        For Each item As myObject In myList
            i += 1
            sb.Append("<tr><td>")            
            sb.Append("<textarea runat='server' id=txt_comments" & i & " 
                        name='txt_comments' rows='5' cols='60'></textarea></td>")          
            sb.Append("</tr>")
         Next        
        sb.Append("</table>")
        myDiv.InnerHtml = sb.ToString 
      
     End Sub  





从上面的代码中,

我在页面加载时动态创建



From the above code,
I am creating

<textarea>

HTML控件通过使用stringbuilder和最后的屁股将此字符串连接到我的div,该字节存在于.aspx页面中



HTML control dynamically on Page load by using stringbuilder and finally assiging this string to my div which is present in .aspx page

<div id="myDiv" runat="server">





我能够在页面加载时查看动态创建的控件。



现在我想在按钮点击事件中保存这些文本框中的值(保存)。



我该怎么做?

任何帮助?

提前致谢。





我的尝试:



我尝试使用Page.FindControl方法。但它抛出了空引用错误。



I am able to view my dynamically created controls on Page load.

Now I want to access the values from these textboxes in a button click event(Save).

How do i do that?
Any Help?
Thanks in advance.


What I have tried:

I tried using Page.FindControl method. But it is throwing null reference errors.

推荐答案

忘记runat属性,这对于以这种方式创建的控件无效,这些控件实际上是基本的html控件。其次你需要一个唯一的元素名称,也可以使它与id相同



Forget the "runat" attribute, that doesn't work on controls created this way which are effectively basic html controls. Second you need a unique name for the element, might as well make it the same as the id

sb.Append("<textarea id=txt_comments" & i & " 
                        name='txt_comments" & i & "' rows='5' cols='60'></textarea></td>")   





在您的代码隐藏中,您可以根据名称来读取Request.Form集合中的值





In your code-behind you can read the value from the Request.Form collection based on the name

Request.Form("txt_comments1")





替代方案是实际创建像TextBox这样的服务器端控件,并将其添加到页面的Controlls集合中。如果你谷歌asp.net创建动态控件,你会发现很多如何做到这一点的例子。



The alternative would be to actually create server-side controls like a TextBox and add it to the page's Controlls collection. If you google "asp.net create dynamic controls" you'll find lots of examples of how to do that.


这篇关于如何从ASP.NET中动态创建的HTML控件访问值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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