Dynamic Textboxes losing their values on postback

40 Views Asked by At

I'm creating a web app in ASP.NET (web forms) and there's a part where I have to generate dynamic textboxes, I am able to do that but values I entered in textboxes disappears after button click. I have read many solutions on community but it does not work for me.

Here's my code of aspx

  <asp:Panel ID="pnlTextBoxes" runat="server"></asp:Panel>
  <asp:Button ID="Button1" runat="server" Text="Add New" OnClick="btnAddTextBox_Click" />
  <asp:Button ID="Button2" runat="server" Text="Remove TextBox" OnClick="btnRemoveTextBox_Click" />

Here's code of code behind


protected void btnAddTextBox_Click(object sender, EventArgs e)
{
    int controlsCount = (int)(ViewState["ControlsCount"] ?? 0);
    controlsCount++;
    ViewState["ControlsCount"] = controlsCount;
    GenerateControls(controlsCount);
}

protected void btnRemoveTextBox_Click(object sender, EventArgs e)
{
    int controlsCount = (int)(ViewState["ControlsCount"] ?? 0);
    if (controlsCount > 0)
    {
        controlsCount--;
        ViewState["ControlsCount"] = controlsCount;
        GenerateControls(controlsCount);
    }
}
string[] baseIds = new string[] { "DSrNo", "DDescShBx", "DTtlBx", "DBNo", "DExpDt", "DHsnCd", "DTtlQty", "DRteUsd", "DAmtUsd" };
private void GenerateControls(int controlsCount)
{
    string[] labelTexts = new string[] { "Sr No.", "Desc. of Shipper Box", "Total Box", "Batch No", "Exp Date", "HSN Code", "Total qty",
        "Rate in Usd", "Amount in USD" };

    string[] colClasses = new string[] { "col-12 col-lg-1 mb-3", "col-12 col-lg-2 mb-3", "col-12 col-lg-1 mb-3", "col-12 col-lg-1 mb-3",
        "col-12 col-lg-1 mb-3", "col-12 col-lg-1 mb-3", "col-12 col-lg-1 mb-3", "col-12 col-lg-2 mb-3", "col-12 col-lg-2 mb-3" };
    if (pnlTextBoxes == null)
    {
        pnlTextBoxes = new Panel();
      
    }
  
    for (int i = 0; i < controlsCount; i++)
    {
        Panel row = new Panel();
        row.CssClass = "row";
      

        for (int j = 0; j < baseIds.Length; j++)
        {
            TextBox txt = new TextBox();
            txt.ID = $"{baseIds[j]}_{i}";
            txt.CssClass = "form-control";
            EnableViewState=true;
          
        
            Label lbl = new Label();
            lbl.Text = labelTexts[j % labelTexts.Length]; 
            lbl.ID = $"lbl{baseIds[j]}_{i}";

            Panel col = new Panel();
            col.CssClass = "col-12 col-lg-" + colClasses[j % colClasses.Length]; 
            col.Controls.Add(lbl);
            col.Controls.Add(txt);

            row.Controls.Add(col);
        }
       


        pnlTextBoxes.Controls.Add(row);
    }
}

When user click on add text box button it add nine textboxes and on remove button it removes textboxes, But if I enter any value in textbox values entered in textboxes gets erased. It does not maintain its value to postback.

0

There are 0 best solutions below