0

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.

Shyam Vemula
  • 591
  • 2
  • 14
  • When reading the values, what is in `divQtn.Controls`? Where in the overall page life cycle are you performing either of these operations? Are the form values themselves included in the `Request`? – David Aug 10 '17 at 12:29
  • divQtn.Controls getting Count as '1' and {InnerText="\r\n\r\n "} @David – Shyam Vemula Aug 10 '17 at 12:38
  • are you are getting null on this line `string txtData = txt.Text;` ? because i think you should get an error on this line `TextBox txt = (TextBox)divQtn.FindControl(txtID);` if the textbox not found – Amr Elgarhy Aug 10 '17 at 12:45

3 Answers3

1

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);
    }
}
Win
  • 61,100
  • 13
  • 102
  • 181
0

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"];
IronAces
  • 1,857
  • 1
  • 27
  • 36
Melih Yilman
  • 49
  • 3
  • 11
0

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;
}
Melih Yilman
  • 49
  • 3
  • 11