Combine Foreach Loop And Counter To Add Dynamically Generated Html To The Beginning And End Of Every Nth Row
I am dynamically generating HtmlGeneric Controls with data in a DataTable. I need to concatenate HTML to the beginning and end of each group of 3. For example, my table looks somet
Solution 1:
Shane, what you are essentially doing is Paging through your Rows in your table, so focus on Skip and Take Linq extension methods. Below is a hasty sample
voidMain()
{
// Data table that we are trying to page trough
List<string> rows = new List<string>()
{
" title1,body1 ",
" title2,body2 ",
" title3,body3 ",
" title4,body4 ",
" title5,body5 ",
" title6,body6 ",
" title7,body7 "
};
//Result after paging
List<string> group = new List<string>();
// Set your page size or pass in as a parameterint numberOfObjectsPerPage = 3;
decimal totalRows = rows.Count;
int pages = (int) Math.Ceiling(totalRows/numberOfObjectsPerPage);
for(int i=0;i<pages;i++)
{
string rowText = "";
// Get the rows in that page Focus on the Skip and Take methodsvar tempRows = rows.Skip(i * numberOfObjectsPerPage).Take(numberOfObjectsPerPage);
// Now foreach page do something hereforeach(var row in tempRows)
{
rowText = rowText + row.ToString();
}
group.Add("div group" + rowText + "/div" );
};
group.ForEach( g =>
{
Console.WriteLine(g);
});
}
you get something like this.
div group title1,body1 title2,body2 title3,body3 /divdiv group title4,body4 title5,body5 title6,body6 /divdiv group title7,body7 /div
Solution 2:
I think it's a good way to use two methods, one for creating start tag
and one for end tag
if needed, like this:
int counter=0, quantity;//make these global in your classpublicvoidCreateHtml()
{
DataTable dtCards = GetData();
quantity= dt.Rows.Count;
foreach (DataRow row in dtCards.Rows)
{ counter++;
EndCardGroup();
StartCardGroup();
var titleText = row["Title"].ToString();
var bodyText = row["Body"].ToString();
CreateDiv(titleText, bodyText); //method to create HmtlGeneric Controls
}
}
privatevoidStartCardGroup()
{
if (counter % 3 == 0 || counter == 1)
{
//you code to create start 'CardGroup' div
}
}
privatevoidEndCardGroup()
{
if (counter %3 == 0 || counter==quantity)
{
//you code to create end 'CardGroup' div
}
}
Of course you can use for
statment instead of foreach
. and you can make DataTable
global to use its Row.Count
to get rid of counter
and quantity
.
Post a Comment for "Combine Foreach Loop And Counter To Add Dynamically Generated Html To The Beginning And End Of Every Nth Row"