Wednesday 16 March 2011

Adding & Removing GridView columns in the Print Preview using JavaScript



This post concentrates on the implementation of the following two requirements:
  1. Show print preview using JavaScript when the GridView required in the preview by hiding some of the columns shown on the normal screen (like Edit, Delete columns).
  2. Show print preview using JavaScript when the GridView required in the preview by adding some additional column which is not visible in the normal page. (normally we show important columns in the normal page, but the print show all the columns)

The base concept behind this implementation is as follows:
  • Declare two css class one is for displaying (ColVisible) the columns and another one for hiding (ColInVisible) the columns.
  • In the design script of the GridView, assign the ColVisible for the columns which required being visible on the page and not in the print. (This makes Visible on the page but in print JavaScript will change the css style to ColInVisible for that column)
  • Also assign ColInVisible for the columns which are required to be hidden on the page and visible on the print. (This makes hidden on the page but in print JavaScript will change the css style to ColVisible for that column)
  • In the Javascript before assigning InnerHTML, replace the script by changing ColVisible to ColInVisible and ColInVisible to ColVisible.

I am using NorthWind Database for this example. So please make sure you have NorthWind Setup to run the same code.

Following is the implementation of the requirement –

In aspx script.
<div id="GridViewContainer">
    <asp:GridView ID="grdViewProducts" runat="server" 
        AllowPaging="True" AutoGenerateColumns="False" TabIndex="1"
        DataKeyNames="ProductID" Width="100%" CssClass="GridViewStyle"
        ShowFooter="false" CellPadding="4" ForeColor="#333333" GridLines="None" 
        OnPageIndexChanging="grdViewProducts_PageIndexChanging">
        <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
        <Columns>
            <asp:BoundField DataField="ProductName" HeaderText="Product Name" />
            <asp:BoundField DataField="CompanyName" HeaderText="Supplier" />
            <asp:BoundField DataField="CategoryName" HeaderText="Category" />
            <asp:BoundField DataField="QuantityPerUnit" HeaderText="Quantity Per Unit"/>
            <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" />
            <asp:BoundField DataField="UnitsInStock" HeaderText="Units In Stock" ItemStyle-CssClass="ColInVisible" HeaderStyle-CssClass="ColInVisible" FooterStyle-CssClass="ColInVisible" />
            <asp:BoundField DataField="UnitsOnOrder" HeaderText="Units On Order" ItemStyle-CssClass="ColInVisible" HeaderStyle-CssClass="ColInVisible" FooterStyle-CssClass="ColInVisible" />
            <asp:BoundField DataField="ReorderLevel" HeaderText="Reorder Level" ItemStyle-CssClass="ColInVisible" HeaderStyle-CssClass="ColInVisible" FooterStyle-CssClass="ColInVisible" />
            <asp:CommandField ShowDeleteButton="True" HeaderText="Delete" ItemStyle-CssClass="ColVisible" HeaderStyle-CssClass="ColVisible" FooterStyle-CssClass="ColVisible" />
            <asp:CommandField ShowSelectButton="True" HeaderText="Edit" ItemStyle-CssClass="ColVisible" HeaderStyle-CssClass="ColVisible" FooterStyle-CssClass="ColVisible" />
        </Columns>
        
        <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
        <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
        <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
        <EditRowStyle BackColor="#999999" />
        <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
        
    </asp:GridView>
    <input type="button" value="Print" onclick="PrintGridView()" />
    <asp:HiddenField ID="hndGridViewPrintContent" runat="server" />
</div>
JavaScript
function PrintGridView() {
    printWindow = window.open("", "mywindow", "location=0,status=0,scrollbars=1,resizable=1");

    var strContent = "<html><head>";
    strContent = strContent + "<title" + ">Print Preview</title>";
    strContent = strContent + "<link href=\"App_Themes/Default/Default.css\" type=\"text/css\" rel=\"stylesheet\" />";
    strContent = strContent + "</head><body>";
    strContent = strContent + "<div style='width:100%;text-align:right;'>";
    strContent = strContent + "<input type='button' id='btnPrint' value='Print' style='width:100px' onclick='window.print()' />";
    strContent = strContent + "<input type='button' id='btnCancel' value='Cancel' style='width:100px' onclick='window.close()' />";
    strContent = strContent + "</div>";

    // Removing/Invisibiling Columns
    strContent = strContent + "<div style='width:100%;'>";
    var GridViewContent = document.getElementById('<%= hndGridViewPrintContent.ClientID %>').value;
    
    //Assigning a Temproary Class name, as ColVisible will be replaced by next line
    GridViewContent = GridViewContent.replace(/ColInVisible/g, "ColIVisible");
    GridViewContent = GridViewContent.replace(/ColVisible/g, "ColInVisible");
    GridViewContent = GridViewContent.replace(/ColIVisible/g, "ColVisible");
    
    strContent = strContent + GridViewContent;
    strContent = strContent + "</div>";

    strContent = strContent + "</body>";
    printWindow.document.write(strContent);
    printWindow.document.close();
    printWindow.focus();
}
Style Sheet
body
{
    margin:5px;
}
.ColVisible
{
    display:block;
}
.ColInVisible
{
    display:none;
}
.GridViewStyle
{
    font-family:Calibri;
    font-size:12px;
}
C# Codebehind
protected void Page_PreRender(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        grdViewProducts.AllowPaging = false;
        BindGrid();
        System.IO.StringWriter stringwriter = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlwriter = new System.Web.UI.HtmlTextWriter(stringwriter);
        grdViewProducts.RenderControl(htmlwriter);
        hndGridViewPrintContent.Value = stringwriter.ToString();

        grdViewProducts.AllowPaging = true;
        BindGrid();
    }
}
private void BindGrid()
{
    using (SqlConnection connection =
        new SqlConnection(ConfigurationManager.ConnectionStrings
                            ["SQLConnection"].ConnectionString))
    {

        SqlCommand command = new SqlCommand(
               "SELECT ProductID, ProductName, CompanyName, CategoryName, " +
               "QuantityPerUnit, UnitPrice, UnitsInStock, UnitsOnOrder, ReorderLevel FROM Products " +
               "JOIN Suppliers ON Products.SupplierID = Suppliers.SupplierID " +
               "JOIN Categories ON Products.CategoryID = Categories.CategoryID " +
               "Order by ProductID", connection);

        connection.Open();
        SqlDataReader dr = command.ExecuteReader(CommandBehavior.CloseConnection);

        IList<ProductView> productViewList = new List<ProductView>();
        while (dr.Read())
        {
            ProductView productView = new ProductView();
            productView.ProductID = dr["ProductID"].ToString();
            productView.ProductName = dr["ProductName"].ToString();
            productView.CompanyName = dr["CompanyName"].ToString();
            productView.CategoryName = dr["CategoryName"].ToString();
            productView.QuantityPerUnit = dr["QuantityPerUnit"].ToString();
            productView.UnitPrice = Convert.ToDouble(dr["UnitPrice"].ToString());
            productView.UnitsInStock = Convert.ToInt32(dr["UnitsInStock"].ToString());
            productView.UnitsOnOrder = Convert.ToInt32(dr["UnitsOnOrder"].ToString());
            productView.ReorderLevel = Convert.ToInt32(dr["ReorderLevel"].ToString());
            productViewList.Add(productView);
        }
        grdViewProducts.DataSource = productViewList;
        grdViewProducts.DataBind();
    }
}
protected void grdViewProducts_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    grdViewProducts.PageIndex = e.NewPageIndex;
    BindGrid();
}
public override void VerifyRenderingInServerForm(Control control)
{
    return;
}
public class ProductView
{
    public string ProductID { get; set; }
    public string ProductName { get; set; }
    public string CompanyName { get; set; }
    public string CategoryName { get; set; }
    public string QuantityPerUnit { get; set; }
    public double UnitPrice { get; set; }
    public int UnitsInStock { get; set; }
    public int UnitsOnOrder { get; set; }
    public int ReorderLevel { get; set; }
}
Here is the output of the example.
GridView with Delete, Edit columns
Preview window by removing Edit, Delete columns and adding three columns
download the source code here

1 Response to “Adding & Removing GridView columns in the Print Preview using JavaScript”

Post a Comment