简体   繁体   English

无法在C#中获取动态文本框文本

[英]Unable to get dynamic textbox text in C#

I created the dynamic textboxes and placed in div on Webpage. 我创建了动态文本框,并将其放在网页上的div中。 But I am unable to read the text in the created textboxes. 但是我无法阅读创建的文本框中的文本。 For Creating I used below code (Sample). 对于创建,我使用了以下代码(示例)。 This is my design code in .aspx 这是我在.aspx中的设计代码

<div ID="divQtn" runat="server">

for(int i=0;i<5;i++)
{
 TextBox txt = new TextBox();
 txt.ID="txt"+i.ToString();
 txt.Attributes.Add("runat","server");
 divQtn.Controls.Add(txt);
}

For Reading text from textbox: 从文本框中读取文本:

for(int i=0;i<5;i++)
{
 string txtID = "txt"+i.ToString();
 TextBox txt = (TextBox)divQtn.FindControl(txtID);
 string txtData = txt.Text;
}

I am getting txt as Null. 我将txt设为Null。

Dynamic controls in ASP.NET Web Form are a little bit tricky. ASP.NET Web窗体中的动态控件有些棘手。 You will need to reload them back with same id inside Page_Init (or Page_Load) event. 您需要在Page_Init (或Page_Load)事件中以相同的ID重新加载它们。

<asp:PlaceHolder runat="server" ID="PlaceHolder1"></asp:PlaceHolder>
<asp:Button runat="server" ID="SubmitButton" Text="Submit" 
   OnClick="SubmitButton_Click" />

Code Behind 背后的代码

protected void Page_Init(object sender, EventArgs e)
{
    CreateDynamicControls();
}

private void CreateDynamicControls()
{
    for (int i = 0; i < 5; i++)
    {
        TextBox txt = new TextBox();
        txt.ID = "txt" + i;
        PlaceHolder1.Controls.Add(txt);
    }
}

protected void SubmitButton_Click(object sender, EventArgs e)
{
    IList<string> data = new List<string>();
    for (int i = 0; i < 5; i++)
    {
        string txtID = "txt" + i;
        TextBox txt = (TextBox)PlaceHolder1.FindControl(txtID);
        data.Add(txt.Text);
    }
}

Can you try following ? 你可以试试看吗? :

TextBox txt = divQtn.FindControl(txtID) as TextBox; 
string txtData = txt.Text.ToString();

or that should be work 还是应该工作

String sValue=Request.Form["ID HERE"];

2nd option is u can add event handler like a that: 第二个选择是,您可以像这样添加事件处理程序:

 TextBox txt = new TextBox();
    //add the event handler here
    txt.TextChanged += new EventHandler(System.EventHandler(this.txt_TextChanged));

string yourtext;

private void txt_TextChanged(object sender, EventArgs e)
{
    yourText = (sender as TextBox).Text;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM