سؤال

I have a bit of a dilemma. I have a dynamic number of items that I would like to convert into a htmlTable that will allow me to dynamically determine the number of columns and rows that I want the table to have.

For example, say I have a list of 5 items. I would like to be able to have the table built and rendered dynamically as a 1x1, 2x1, 2x2, etc..

This is what I was able to come up with so far, but I keep getting an out of range error which tells me I haven't got the logic down for creating the right number of cells before adding the list of items. I got stuck trying to figure out how to build the table while accounting for the custom columns, rows, and the dynamic list.

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

int desiredNumberOfColumns = 1; //How many Columns I want
int desiredNumberOfRows = 5; //How many Rows I want

int customColumn = desiredNumberOfColumns / rivers.Count;
int customRow = desiredNumerOfColumns % rivers.Count;

List<string> rivers = new List<string>(new string[]
{
    "nile",
    "amazon",     // River 2
    "yangtze",    // River 3
    "mississippi",
    "yellow"
});


    for(int i=0; i<(desiredNumberOfRows / rivers.Count); i++) //
    {
       row = new HtmlTableRow();
       for(int j=0;j<(customRow / rivers.Count);++j)
       {
          row.Cells.Add(new HtmlTableCell(rivers[i]));
       }
       myTable.Rows.Add(row);
    }

This example should build a table with 5 rows, and 1 column that looks like the following:

___________
Row |Column
 0  |nile
 0  |amazon
 0  |yangtze
 0  |mississippi
 0  |yellow
-----------
هل كانت مفيدة؟

المحلول

Instead of using two loops, with divisions and mods (which could provide funny values) try it with one loop.

int totalObjects = rivers.Count;
int totalCells = desiredRows * desiredColumns;
HtmlTableRow newRow = new HtmlTableRow();
for( i = 0; i < totalCells; i++ )
{
    // make a new row when you get the desired number of columns
    // skip the first, empty row
    if( i % desiredColumns == 0 && i != 0 )
    {
        myTable.Rows.Add( newRow );
        newRow = new HtmlTableRow();
    }
    // keep putting in cells
    if( i < totalObjects )
        row.Cells.Add(new HtmlTableCell(rivers[i]));
    // if we have no more objects, put in empty cells to fill out the table
    else
        row.Cells.Add(new HtmlTableCell(""));
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top