Tajkumar
Tajkumar

Reputation: 441

How to add text boxes dynamically in asp.net C# and use the textbox values after adding

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;

Upvotes: 0

Views: 1340

Answers (1)

Irfan TahirKheli
Irfan TahirKheli

Reputation: 3662

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

Upvotes: 1

Related Questions