Add table with alternate row colors using Aspose.PDF for .NET by importing data from DataTable

I want alternating row background colors for cells in a table that is created using ImportDataTable.

How do I loop through the rows collection and set the cell background color? Thanks.

Hi,

The following code should do the trick:

/* Create a DataTable object (Employee) and add columns to it (Employee_ID,
* Employee_Name, Gender).
*/
DataTable dt = new DataTable("Employee");
dt.Columns.Add("Employee_ID", typeof(Int32));
dt.Columns.Add("Employee_Name", typeof(string));
dt.Columns.Add("Gender", typeof(string));
//Add 4 rows into the DataTable object programmatically
DataRow dr = dt.NewRow();
dr[0] = 1;
dr[1] = "John Smith";
dr[2] = "Male";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = 2;
dr[1] = "Mary Miller";
dr[2] = "Female";
dt.Rows.Add(dr);

dr = dt.NewRow();
dr[0] = 3;
dr[1] = "John Doe";
dr[2] = "Male";
dt.Rows.Add(dr);

dr = dt.NewRow();
dr[0] = 4;
dr[1] = "Jane Doe";
dr[2] = "Female";
dt.Rows.Add(dr);

//Instantiate a Pdf instance
Pdf pdf1 = new Pdf();
//Create a section in the Pdf instance
Aspose.Pdf.Section sec1 = pdf1.Sections.Add();
//Create a Table object
Aspose.Pdf.Table tab1 = new Aspose.Pdf.Table();
//Add the Table object in the paragraphs collection of the section
sec1.Paragraphs.Add(tab1);
//Set column widths of the table
tab1.ColumnWidths = "40 100 100 100";
//Set default cell border of the table using BorderInfo object
tab1.DefaultCellBorder = new BorderInfo((int)BorderSide.All, 0.1F);
//Import data into the Table object from the DataTable created above
tab1.ImportDataTable(dt, true, 0, 1, 4, 3);

//Get 1st row from the table
//Row row1 = tab1.Rows[0];
bool altColor = false;
//Iterate through all cells in the row and set their background color to blue
foreach (Aspose.Pdf.Row curRow in tab1.Rows)
{
altColor = !altColor;
foreach (Aspose.Pdf.Cell curCell in curRow.Cells)
if (altColor)
curCell.BackgroundColor = new Aspose.Pdf.Color("Blue");
else
curCell.BackgroundColor = new Aspose.Pdf.Color("Red");
}
//Save the Pdf
pdf1.Save("Table.pdf");

Thanks.

Adeel Ahmad
Support Developer
Aspose Changsha Team
http://www.aspose.com/Wiki/default.aspx/Aspose.Corporate/ContactChangsha.html