0

I am able to add textboxes dynamically and i am not able to use the value of the textboxes which are dynamically added Here is my code

int i = 0;
List<string> controlidlist = new List<string>();
protected override void LoadViewState(object savedState)
{
    base.LoadViewState(savedState);
    controlidlist = (List<string>)ViewState["controlidlist"];
    foreach (string Id in controlidlist)
    {
        i++;
        TextBox tb = new TextBox();
        tb.ID = Id;
        LiteralControl lineBreak = new LiteralControl();
        PlaceHolder1.Controls.Add(tb);
        PlaceHolder1.Controls.Add(lineBreak);
    }
}

Here am performing the dynamically adding the textboxes

   protected void Button1_Click(object sender, EventArgs e)
{

    i++;
    TextBox tb = new TextBox();
    tb.ID = "textboxes" + i;
    tb.Text = "textbox" + i;

    LiteralControl lineBreak = new LiteralControl("<br>");
    PlaceHolder1.Controls.Add(tb);
    PlaceHolder1.Controls.Add(lineBreak);
    controlidlist.Add(tb.ID);
    ViewState["controlidlist"] = controlidlist;

}

Here i want to try get the textbox values which are dynamically added

  protected void datainput_Click(object sender, EventArgs e)
{
    string m = string.Empty;
    for (int f = 0; f < i; f++)
    {
        TextBox t = (TextBox)FindControl("textboxes"+f);
        string k = t.Text;
        m = m +","+k;


        }
    string h = m;
}

The error which am getting is "Object reference not set to an instance of an object". at string k = t.Text;

1 Answer 1

1

Add it to a container:

<asp:Panel runat="server" ID="pnlTextboxes"></asp:Panel>

 foreach (string Id in controlidlist)
    {
        i++;
        TextBox tb = new TextBox();
        tb.ID = Id;
        LiteralControl lineBreak = new LiteralControl();
        pnlTextboxes.Controls.Add(tb);
        pnlTextboxes.Controls.Add(lineBreak);
    }

and :

 TextBox t = (TextBox)pnlTextboxes.FindControl("textboxes"+f);

UPDATE:

TextBox t = (TextBox)PlaceHolder1.FindControl("textboxes"+f);
Sign up to request clarification or add additional context in comments.

2 Comments

should i replace place holder and add it to the panel
if you are using placeholder then search it inside placeholder. see updated answer @user3630591

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.