Luis
Luis

Reputation: 341

ASP.NET and C# fill a table with data from database

I've created a table with some C# and asp.net for be filled by data from a database, but when I add data to the table, the data is going to the same row. I want to put data in multiple rows.

Some code I have used is:

int tmp = 0;
TableRow tabelaLinhas = new TableRow();
while (tmp < dados.Rows.Count)
{
 TableCell celula = new TableCell();
 celula.Controls.Add(new LiteralControl(dados.Rows[tmp]["nome"].ToString()));
 tabelaLinhas.Cells.Add(celula);
 tabela.Rows.Add(tabelaLinhas);

 CheckBox caixa = new CheckBox();
 caixa.ID = dados.Rows[tmp]["nome"].ToString().Replace(" ", "").ToLower() + "CheckBox";
 celula = new TableCell();
 celula.Controls.Add((Control)caixa);
 tabelaLinhas.Cells.Add(celula);
 tabela.Rows.Add(tabelaLinhas);

 tmp++;
}

Upvotes: 2

Views: 4608

Answers (2)

Kubi
Kubi

Reputation: 2169

write

tabelaLinhas = new TableRow();

under

tabela.Rows.Add(tabelaLinhas);

Upvotes: 0

Brian Mains
Brian Mains

Reputation: 50728

Move

TableRow tabelaLinhas = new TableRow(); 

into the while loop; you are only creating one row object, even though you are adding multiple times. New instances need created in every while iteration.

HTH.

Upvotes: 2

Related Questions