0

I have an asp:Table, have defined the header cells in .aspx page. Have an AddRow button, which when clicked should add a new row to the table.

The code is as follows:

<asp:Table ID="tblnew" runat="server" BorderStyle="Inset" GridLines="Vertical">
            <asp:TableRow>
                <asp:TableCell>S.NO</asp:TableCell>
                <asp:TableCell>Service</asp:TableCell>
                <asp:TableCell>Material Type</asp:TableCell>
                <asp:TableCell>
                    <asp:Button ID="btnAddRow" runat="server" Text="Add Row" OnClick="CreateRow" />
                </asp:TableCell>
            </asp:TableRow>
        </asp:Table>

The code behind is:

protected void CreateRow(object sender, EventArgs e)
        {
            TableRow tr = new TableRow();
            tblnew.Controls.Add(tr);
            for (int i = 0; i < 3; i++)
            {
                TableCell tc = new TableCell();
                TextBox txt = new TextBox();
                tc.Controls.Add(txt);
                tr.Controls.Add(tc);
            }
            TableCell tc1 = new TableCell();
            Button btn = new Button();
            btn.Text = "Remove";
            tc1.Controls.Add(btn);
            tr.Controls.Add(tc1);
        }

Things work fine when AddRow button is clicked for the first time.

A new row gets added, but when I click the AddRow button again, another row doesn't get added. I guess I'm missing some key stuff here.

Also, I have not written any code on Remove button click, yet it removes the particular row when clicked, guess maybe some postback stuff is happening.

On Page_Load:

enter image description here

After AddRow button click: enter image description here

Experts please help.

Anurag
  • 552
  • 9
  • 31

1 Answers1

0

Because of PosBack your added row doesn't persist, You can use ViewState.

Or take a look at:

Dynamic generated TableRows

Or here is your answer discussed about how to generate rows of TextBoxes in ASP Table on every click of the Button and retain the entered values on postbacks:

Dynamic Table Row.

Hope this will help you.

Community
  • 1
  • 1
Aria
  • 3,724
  • 1
  • 20
  • 51