Partilhar via


Como: Adicionar linhas e células dinamicamente a tabela controle de servidor Web

It is common to add rows and cells to a Table Web server control at run time.The Table Web server control is designed specifically for this task.

Observação:

To design a table visually in Design view, use an HtmlTable control.If you also need to programmatically manipulate the contents of the HtmlTable control, convert its rows and cells to HtmlTableRow and HtmlTableCell controls by setting their runat attribute to server.For details, see Converting HTML Server Controls to HTML Elements.

Rows in a Table Web server control are objects of type TableRow.The Rows property of the Table control supports a collection of TableRow objects.To add a row to the table, you add a TableRow object to this collection.

Similarly, the TableRow object has a Cells property that supports a collection of objects of type TableCell.You can add cells to a row by manipulating this collection.

Para adicionar linhas e células a uma tabela dinamicamente

  1. To add a row, create a new object of type TableRow:

    Dim tRow As New TableRow()
    Table1.Rows.Add(tRow)
    
    TableRow tRow = new TableRow();
    Table1.Rows.Add(tRow);
    
  2. To add cells to the row, create one or more objects of type TableCell:

    Dim tCell As New TableCell()
    tRow.Cells.Add(tCell)
    
    TableCell tCell = new TableCell();
    tRow.Cells.Add(tCell);
    
  3. Adicione conteúdo à nova célula.Você pode fazer isso de várias maneiras, como mostrado na tabela a seguir.

    Para adicionar

    Faça isso

    Texto estático

    Set the cell's Text property.

    Controles

    Declare an instance of the control and add it to the cell's Controls collection.

    Texto e controles na mesma célula

    Declare the text by creating an instance of the Literal class.Add it to the cell's Controls collection as you would other controls.

    Observação:

    Por padrão, controles que você adicionar dinamicamente a uma página de Web Forms são adicionados ao estado da exibição da página.Se você recriar controles em cada processamento, isso pode resultar em um comportamento inesperado quando a página é processada, porque o estado da exibição é restaurado antes de os controles serem recriados.You can avoid problems by setting the EnableViewState property of the container control (for example, of the Table control) to false.Para obter mais informações, consulte Adicionando Controles ASP.NET por Programação.

    The following code example shows how you can add rows and cells to a Table control.The number of rows and columns is determined by what the user enters into two text boxes.Each cell displays the row and cell number as static text.

    Protected Sub Button1_Click(ByVal sender As Object, _
            ByVal e As System.EventArgs) Handles Button1.Click
       ' Total number of rows.
       Dim rowCnt As Integer
       ' Current row count
       Dim rowCtr As Integer
       ' Total number of cells (columns).
       Dim cellCtr As Integer
       ' Current cell counter.
       Dim cellCnt As Integer
    
       rowCnt = CInt(Textbox1.Text)
       cellCnt = CInt(Textbox2.Text)
    
       For rowCtr = 1 To rowCnt
          Dim tRow As New TableRow()
          For cellCtr = 1 To cellCnt
             Dim tCell As New TableCell()
             tCell.Text = "Row " & rowCtr & ", Cell " & cellCtr
             ' Add new TableCell object to row.
             tRow.Cells.Add(tCell)
          Next
          ' Add new row to table.
          Table1.Rows.Add(tRow)
       Next
    
    End Sub
    
    protected void Button1_Click (object sender, System.EventArgs e)
    {
       // Total number of rows.
       int rowCnt;
       // Current row count.
       int rowCtr;
       // Total number of cells per row (columns).
       int cellCtr;
       // Current cell counter
       int cellCnt;
    
       rowCnt = int.Parse(TextBox1.Text);
       cellCnt = int.Parse(TextBox2.Text);
    
       for(rowCtr=1; rowCtr <= rowCnt; rowCtr++) {
          // Create new row and add it to the table.
          TableRow tRow = new TableRow();
          Table1.Rows.Add(tRow);
          for (cellCtr = 1; cellCtr <= cellCnt; cellCtr++) {
             // Create a new cell and add it to the row.
             TableCell tCell = new TableCell();
             tCell.Text = "Row " + rowCtr + ", Cell " + cellCtr;
             tRow.Cells.Add(tCell);
          }
       }
    }
    

    The following code example is similar to the previous one, but displays static text and a HyperLink control in each cell.The HyperLink controle navega para um URL prototipada, passando um protótipo de ID do produto. sistema autônomo o exemplo combina texto estático e controles, o texto estático é implementado sistema autônomo um Literal objeto, que é adicionado à célula Controls coleção sistema autônomo o HyperLink o controle é.

    Protected Sub Button1_Click(ByVal sender As Object, _
            ByVal e As System.EventArgs) Handles Button1.Click
       ' Total number of rows.
       Dim rowCnt As Integer
       ' Current row count
       Dim rowCtr As Integer
       ' Total number of cells (columns).
       Dim cellCtr As Integer
       ' Current cell counter.
       Dim cellCnt As Integer
    
       rowCnt = CInt(TextBox1.Text)
       cellCnt = CInt(TextBox2.Text)
    
       For rowCtr = 1 To rowCnt
          Dim tRow As New TableRow()
          For cellCtr = 1 To cellCnt
             Dim tCell As New TableCell()
             ' Mock up a product ID
             Dim prodID As String
             prodID = rowCtr & "_" & cellCtr
    
             ' Create literal text as control.
             Dim s As New LiteralControl()
             s.Text = "Buy: "
             ' Add to cell.
             tCell.Controls.Add(s)
             ' Create Hyperlink Web Server control and add to cell.
             Dim h As New HyperLink()
             h.Text = rowCtr & ":" & cellCtr
             h.href = "https://www.microsoft.com/net"
             ' Add cell to row.
             tCell.Controls.Add(h)
             ' Add new TableCell object to row.
             tRow.Cells.Add(tCell) 
          Next cellCtr
          ' Add new row to table.
          Table1.Rows.Add(tRow) 
       Next rowCtr
    End Sub
    
    Protected void Button1_Click (object sender, System.EventArgs e)
    {
       // Total number of rows.
       int rowCnt;
       // Current row count.
       int rowCtr;
       // Total number of cells per row (columns).
       int cellCtr;
       // Current cell counter.
       int cellCnt;
    
    
       rowCnt = int.Parse(TextBox1.Text);
       cellCnt = int.Parse(TextBox2.Text);
    
       for(rowCtr=1; rowCtr <= rowCnt; rowCtr++) {
          // Create a new row and add it to the table.
          TableRow tRow = new TableRow();
          Table1.Rows.Add(tRow);
          for (cellCtr = 1; cellCtr <= cellCnt; cellCtr++) {
             // Create a new cell and add it to the row.
             TableCell tCell = new TableCell();
             tRow.Cells.Add(tCell);               
             // Mock up a product ID.
             string prodID = rowCtr + "_" + cellCtr;
    
             // Add a literal text as control.
             tCell.Controls.Add(new LiteralControl("Buy: "));
             // Create a Hyperlink Web server control and add it to the cell.
             System.Web.UI.WebControls.HyperLink h = new HyperLink();
             h.Text = rowCtr + ":" + cellCtr;
             h.href = "https://www.microsoft.com/net";
             tCell.Controls.Add(h);
          }
       }
    }
    

Consulte também

Referência

Visão Geral do controle de servidor Web Table, TableRow e TableCell