I have a Table in a Web Form in ASP.NET and just below in the same form I added a TextBox in which you fill in the fields to add a new row to the Table. The insertion part in the table works fine, but only once the second time I try to add another row to the table the previous one disappears and this new row stays in its place and so on.
ASP.NET
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Table ID="TableAutores" runat="server" Caption="<b>Autores</b>" BorderWidth="2px" BorderStyle="Solid">
<asp:TableHeaderRow runat="server" Font-Bold="true">
<asp:TableHeaderCell>Nome</asp:TableHeaderCell>
<asp:TableHeaderCell>Sobrenome</asp:TableHeaderCell>
</asp:TableHeaderRow>
<asp:TableRow>
<asp:TableCell>AAA</asp:TableCell>
<asp:TableCell>AAA</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell>BBB</asp:TableCell>
<asp:TableCell>BBB</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell>CCC</asp:TableCell>
<asp:TableCell>CCC</asp:TableCell>
</asp:TableRow>
</asp:Table>
<br />
<asp:Label Text="Nome" runat="server" />
<asp:TextBox ID="TextBoxNome" runat="server" />
<asp:Label Text="Sobrenome" runat="server" />
<asp:TextBox ID="TextBoxSobrenome" runat="server" />
<asp:Button ID="ButtonAdicionar" Text="Adicionar autor" runat="server" OnClick="ButtonAdicionar_Click" />
</div>
</form>
</body>
</html>
C #
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default : System.Web.UI.Page
{
protected void ButtonAdicionar_Click(object sender, EventArgs e)
{
TableCell nome = new TableCell();
TableCell sobrenome = new TableCell();
nome.Text = TextBoxNome.Text;
sobrenome.Text = TextBoxSobrenome.Text;
TableRow linha = new TableRow();
linha.Cells.Add(nome);
linha.Cells.Add(sobrenome);
TableAutores.Rows.Add(linha);
}
}
Apparently I'm inserting the data into the original Table and not into the Table of the postback page. The funny thing is that I did the same with a ListBox and it worked, I was able to add more than one item.
What should I do to be able to add a row in the Table of the postback page (if this is the correct term to use)? Is there an attribute that I need to modify?