codecompleting
codecompleting

Reputation: 9611

How to display only 3 table cells per row when looping through a collection

I am looping through a collection, and generating a htmltable.

I want to only display a maximum of 3 table cells per row.

I need some help with that logic.

My code so far is displaying 1 item per row.

HtmlTable table = new HtmlTable();
HtmlTableRow row;
HtmlTableCell cell;

for(int x = 0; x < userList.Count; x++)
{
   row = HtmlTableRow();

   cell = HtmlTableCell();

   // other stuff

   row.Controls.Add(cell);
   table.Controls.Add(table);
}

Upvotes: 0

Views: 880

Answers (3)

Chandu
Chandu

Reputation: 82913

Try this:

HtmlTable table = new HtmlTable();
HtmlTableRow row;
HtmlTableCell cell;

for(int x = 0; x < userList.Count; x++)
{
            if(x%3 == 0)
            {
                row = new HtmlTableRow();
                table.Controls.Add(row);
            }
   cell = new HtmlTableCell();
   row.Controls.Add(cell);
}

for(int x = 0; x < userList.Count%3; x++)
{
   cell = new HtmlTableCell();
   row.Controls.Add(cell);
}

Upvotes: 1

Pa.M
Pa.M

Reputation: 1402

you can try like this:

HtmlTable table = new HtmlTable();
HtmlTableRow row;
HtmlTableCell cell;

for(int x = 0; x < userList.Count; x++)
{
row = HtmlTableRow();

cell = HtmlTableCell();


// other stuff

 row.Controls.Add(cell);
 if((x+1) % 3 == 0)
{

 table.Controls.Add(row);
}
}

Upvotes: 0

musefan
musefan

Reputation: 48415

I don't see what your issue is? If you want 3 cells, then add 3 cells...

cell = HtmlTableCell();
//set cell 1 data
row.Controls.Add(cell);
cell = HtmlTableCell();
//set cell 2 data
row.Controls.Add(cell);
cell = HtmlTableCell();
//set cell 3 data
row.Controls.Add(cell);

if you want to apply some specific logic based on what data you have in "other stuff" then you need to tell us more about that data

Based on other answer I think I now understand. So each Usercontrol is a cell? If so, you can do

row = HtmlTableRow();
int cellCount = 0;
for(int x = 0; x < userList.Count; x++)
{
   cell = HtmlTableCell();

   // other stuff

   row.Controls.Add(cell);

   cellCount++;

   if(cellCount == 3)
   {
      cellCount = 0;
      table.Controls.Add(row);
      row = HtmlTableRow();
   }
}

Upvotes: 0

Related Questions