Printing GridView Only in ASP.NET

Let's return to the ASP.NET tips and trick series. We are once again going to learn a new trick related to GridView. Previously I posted the following articles related to GridView.

Requirements

Suppose you have a page where you are displaying some data to the user. You want to add functionality to print these records. But the problem with the Browsers Default Print options (Ctrl+P) is that, it will print an entire page. All header images, footers, sidebars and colors will be printed, which is not required. You have two options, either create a new page for a print view and redirect the user to that page or just print the required area, in our case it is the GridView.

Most developers working in a web applications have a MasterPage for their web application. A MasterPage is similar to templates in normal HTML having some advanced functionality and customized code for maintaining an easier and common look of a website or application.

Let's have a look at the following screen to make our requirements more clear.

MasterPage

Code for Default.aspx

This is the code for the GridView.

<asp:GridView runat="server" ID="gvProducts" AutoGenerateColumns="false" AllowPaging="false"

    AlternatingRowStyle-BackColor="Linen" HeaderStyle-BackColor="SkyBlue" Width="100%"

    OnPageIndexChanging="gvProducts_PageIndexChanging" EmptyDataText="Sorry! No Products to List. First Add from Add Product Link.">

    <Columns>

        <asp:TemplateField HeaderText="Product ID">

            <ItemTemplate>

                <asp:Label ID="lblProductID" runat="server" Text='<%#Eval("ProductID")%>' ToolTip="ID of Product as stored in Database."></asp:Label>

            </ItemTemplate>

        </asp:TemplateField>

    </Columns>

    <Columns>

        <asp:TemplateField HeaderText="Product Name">

            <ItemTemplate>

                <asp:Label ID="lblProductName" runat="server" ToolTip="Name of Product" Text='<%#Eval("ProductName")%>'></asp:Label>

            </ItemTemplate>

        </asp:TemplateField>

    </Columns>

    <Columns>

        <asp:TemplateField HeaderText="Brand">

            <ItemTemplate>

                <asp:Label ID="lblBrandName" runat="server" ToolTip="Brand of Product" Text='<%#Eval("BrandName")%>'></asp:Label>

            </ItemTemplate>

        </asp:TemplateField>

    </Columns>

    <Columns>

        <asp:TemplateField HeaderText="Category">

            <ItemTemplate>

                <asp:Label ID="lblProductCat" runat="server" ToolTip="Category of Product" Text='<%#Eval("CategoryName")%>'></asp:Label>

            </ItemTemplate>

        </asp:TemplateField>

    </Columns>

    <Columns>

        <asp:TemplateField HeaderText="In Stock">

            <ItemTemplate>

                <asp:Label ID="lblProductinStock" runat="server" ToolTip="Quantity available in Stock"

                    Text='<%#Eval("UnitsInStock")%>'></asp:Label>

            </ItemTemplate>

        </asp:TemplateField>

    </Columns>

</asp:GridView> 

Code for Default.aspx.cs

We do not have much more at the backend, we are just going to bind data to the GridView.

protected void Page_Load(object sender, EventArgs e)

{

    if (!IsPostBack)

    {

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConToStore"].ConnectionString);

        SqlDataAdapter adp = new SqlDataAdapter("Select * from Products,Brands,Category where Products.BrandID=Brands.BrandID and Products.CategoryID=Category.CategoryID", con);

        DataSet ds = new DataSet();

        adp.Fill(ds);

        gvProducts.DataSource = ds.Tables[0];

        gvProducts.DataBind();

    }

}

Printing the Page

Let's press the Ctrl+P key combination to print the page, before printing see the Preview.

Printing Page

Printing GridView Only

We need to make the following change to print the GridView only. Let's start with the HTML.

Wrap the GridView inside a Table or Panel. I am using a table. Alternatively you can use a Panel.
 

<table width="70%" id="pnlGridView" runat="server" align="center" class="ContentTable">

    <tr>

        <td colspan="2" align="center">

            <h1>

                All Products in Store</h1>

        </td>

    </tr>

    <tr>

        <td>

        </td>

    </tr>

    <tr>

        <td colspan="2">

            <asp:gridview runat="server" id="gvProducts" autogeneratecolumns="false" allowpaging="false"

                alternatingrowstyle-backcolor="Linen" headerstyle-backcolor="SkyBlue" width="100%"

                onpageindexchanging="gvProducts_PageIndexChanging" emptydatatext="Sorry! No Products to List. First Add from Add Product Link.">

...............

.............

</asp:gridview>

        </td>

    </tr>

    <tr>

        <td align="right">

            <asp:linkbutton id="lnkPrint" runat="server" tooltip="Click to Print All Records"

                text="Print Data" onclick="lnkPrint_Click"></asp:linkbutton>

            <asp:linkbutton id="lnkExportAll" runat="server" tooltip="Export this List" text="Export to Excel"

                onclick="lnkExportAll_Click"></asp:linkbutton>

            <asp:linkbutton id="lnkAddNew" runat="server" tooltip="Add New Product" text="Add New"

                onclick="lnkAddNew_Click"></asp:linkbutton>

        </td>

    </tr>

</table>  

Now just add following JavaScript function in head section and assign that function to Print linkbutton.

<script language="javascript" type="text/javascript">

    function PrintPage() {

        var printContent = document.getElementById('<%= pnlGridView.ClientID %>');

        var printWindow = window.open("All Records", "Print Panel", 'left=50000,top=50000,width=0,height=0');

        printWindow.document.write(printContent.innerHTML);

        printWindow.document.close();

        printWindow.focus();

        printWindow.print();

    }

</script>

Now let's click on the Print Link button that we created. The following will be the output of the code above.

Printing GridView Only

Bingo! It satisfies the requirements.

I hope you enjoyed reading this. If you have any feedback or suggestions then please send us as comment or use the contact options. Keep sharing.

To read more blogs: P.R's Blog

Up Next
    Ebook Download
    View all
    Learn
    View all