A table has been created in a webform using C#. The goal is to only print the table when the user clicks the print button on the webform.
Javascript has been implemented in ASP.NET to only print the content within a specific div. While this method works, due to the large number of rows in the table, multiple pages are generated.
There is a need for the table header to be displayed again on each new page. How can this be achieved?
The code snippets include:
<asp:Button ID="printBtn" runat="server" Text="Print" onClientClick="printdiv('tableDiv')" />
<div id="tableDiv">
<asp:Table ID="resultsTable" runat="server" GridLines="Both">
</asp:Table>
</div>
JavaScript for printing:
<script type="text/javascript">
function printdiv(printpage) {
var headstr = "Header";
var footstr = "Footer";
var newstr = document.all.item(printpage).innerHTML;
var oldstr = document.body.innerHTML;
document.body.innerHTML = headstr + newstr + footstr;
window.print();
document.body.innerHTML = oldstr;
return false;
}
</script>
Code behind for the table method:
protected void resultTable()
{
// Database setup codes
...............
try
{
// Database query codes
............
if (reader.HasRows)
{
// Set a table width
resultsTable.Width = Unit.Percentage(60.00);
// Create a new row for adding a table heading
TableRow tableHeading = new TableRow();
// Create and add cells that contain the Name column heading text
TableHeaderCell nameHeading = new TableHeaderCell();
nameHeading.Text = "Name";
nameHeading.HorizontalAlign = HorizontalAlign.Left;
tableHeading.Cells.Add(nameHeading);
TableHeaderCell ageHeading = new TableHeaderCell();
ageHeading.Text = "Age";
ageHeading.HorizontalAlign = HorizontalAlign.Left;
tableHeading.Cells.Add(ageHeading);
resultsTable.Rows.Add(tableHeading);
while (reader.Read())
{
TableRow detailsRow = new TableRow();
TableCell nameCell = new TableCell();
nameCell.Text = reader["name"].ToString();
detailsRow.Cells.Add(nameCell);
TableCell ageCell = new TableCell();
ageCell.Text = reader["age"].ToString();
detailsRow.Cells.Add(ageCell);
resultsTable.Rows.Add(detailsRow);
}
}
reader.Close();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
conn.Close();
}