2009-08-26 7 views
7

Qualcuno può dirmi come creare dinamicamente i tag thead tbody nel mio codice C#?C# create thead and tbody

private void MakeTable() 
{ 
    Table tb = new Table(); 
    TableRow tr = new TableRow(); 
    TableCell td = new TableCell(); 
    td.Text="hello world"; 
    tr.Cells.Add(td); 
    tb.Rows.Add(tr); 
} 

Grazie

+4

In qualche modo l'ho letto come "thread" e non ha assolutamente senso. Scusa per l'interruzione. –

+0

Lo stesso! (15 caratteri fastidiosi per occupare spazio) – Jagd

risposta

20

Ecco un esempio di codice che crea un THEAD TBODY e TFooter.

si può sostanzialmente sempre utilizzare l'oggetto TableRow basta resettare la proprietà TableSection.

Table table = new System.Web.UI.WebControls.Table(); 
    TableRow tableRow; 
    TableCell tableCell; 

    tableRow = new TableRow(); 
    tableRow.TableSection = TableRowSection.TableHeader; 
    tableCell = new TableCell(); 
    tableCell.Text = "HEADER"; 
    tableRow.Cells.Add(tableCell); 
    table.Rows.Add(tableRow); 

    tableRow = new TableRow(); 
    tableRow.TableSection = TableRowSection.TableBody; 
    tableCell = new TableCell(); 
    tableCell.Text = "BODY"; 
    tableRow.Cells.Add(tableCell); 
    table.Rows.Add(tableRow); 

    tableRow = new TableRow(); 
    tableRow.TableSection = TableRowSection.TableFooter; 
    tableCell = new TableCell(); 
    tableCell.Text = "FOOTER"; 
    tableRow.Cells.Add(tableCell); 
    table.Rows.Add(tableRow); 

    plhTest.Controls.Add(table); 

Anche se vorrei suggerire la costruzione della tabella in HTML diretto e aggiungendo alla pagina.

+1

Eventuali motivi specifici per cui suggerirei ("creare la tabella in html diretto e aggiungendo alla pagina")? – Jayesh

+0

Se devi generare questo dinamicamente (ad esempio, per # di colonne sconosciute o altri motivi) ho trovato che TableHeader non eseguirà il rendering come 'thead' UNLESS il TableFooter è stato aggiunto (il footer non può avere celle, ma deve essere aggiunto alla collezione di righe). grrrr. –

+1

Fare attenzione ad aggiungere TableHeaderRow tramite la proprietà Rows della tabella e NON la proprietà controls. L'aggiunta tramite la proprietà Controls equivale a "volte" a significare che l'elemento thead non è reso in html. – Bucket

6

TableRow è fondamentalmente tbody.

Per creare una sezione thead, utilizzare la classe TableHeaderRow anziché una classe TableRow.

(C'è anche, btw, TableFooterRow se si desidera implementare tfoot.

0
var row = new TableHeaderRow() { TableSection = TableRowSection.TableHeader }; 
table.Rows.Add(row); 

dovrebbe fare il trucco