简体   繁体   中英

Unable to get dynamic textbox text in C#

I created the dynamic textboxes and placed in div on Webpage. 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

<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.

Dynamic controls in ASP.NET Web Form are a little bit tricky. You will need to reload them back with same id inside Page_Init (or Page_Load) event.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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