user1830924
user1830924

Reputation: 75

Printing an ASP.NET Web Site page

I have spent 5 days researching how to print a DataList in a C# Visual Studio WEB SITE. I can print the DataList in a Web Project. It appears that since a Site does not have "namespace" as does a Project, Microsoft just didn't bother making a Web Site page printable. I have a rather large Web Site almost developed, and now it appears a major function of a Site is not possible. I need help! Thanks in advance.

P.S. It would seem that Microsoft would have mentioned this little problem in their literature comparing a Project to a Site, but they didn't.

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
 CodeBehind="PageLinkDetails.aspx.cs" Inherits="TestDataBase.PageLinkDetails" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<div>
    <asp:Panel ID="pnl1" runat="server">
        <asp:SqlDataSource runat="server" ID="SqlDataSource1" ConnectionString="<%$ ConnectionStrings:Caribbean %>"
            SelectCommand="SELECT * FROM [CaribbeanDirections] WHERE ([RecipeID] = @RecipeID)">
            <SelectParameters>
                <asp:QueryStringParameter Name="RecipeID" QueryStringField="RecipeID" Type="Int32" />
            </SelectParameters>
        </asp:SqlDataSource>
        <asp:DataList ID="DataList1" runat="server" DataKeyField="DirectionID" DataSourceID="SqlDataSource1">
            <ItemTemplate>
                <asp:Label ID="NameLabel" runat="server" Text='<%# Eval("Name") %>' />
                <br />
                <br />
                INGREDIENTS:<br />
                <asp:Label ID="IngredientOneLabel" runat="server" Text='<%# Eval("IngredientOne") %>' />
                <br />
                <asp:Label ID="IngredientTwoLabel" runat="server" Text='<%# Eval("IngredientTwo") %>' />
                <br />
                <asp:Label ID="IngredientThreeLabel" runat="server" Text='<%# Eval("IngredientThree") %>' />
                <br />
                <asp:Label ID="IngredientFourLabel" runat="server" Text='<%# Eval("IngredientFour") %>' />
                <br />
                <asp:Label ID="IngredientFiveLabel" runat="server" Text='<%# Eval("IngredientFive") %>' />
                <br />
                <asp:Label ID="IngredientSixLabel" runat="server" Text='<%# Eval("IngredientSix") %>' />
                <br />
                <asp:Label ID="IngredientSevenLabel" runat="server" Text='<%# Eval("IngredientSeven") %>' />
                <br />
                <asp:Label ID="IngredientEightLabel" runat="server" Text='<%# Eval("IngredientEight") %>' />
                <br />
                <asp:Label ID="IngredientNineLabel" runat="server" Text='<%# Eval("IngredientNine") %>' />
                <br />
                <asp:Label ID="IngredientTenLabel" runat="server" Text='<%# Eval("IngredientTen") %>' />
                <br />
                Directions:<br />
                <asp:Label ID="DirectionOneLabel" runat="server" Text='<%# Eval("DirectionOne") %>' />
                <br />
                <asp:Label ID="DirectionTwoLabel" runat="server" Text='<%# Eval("DirectionTwo") %>' />
                <br />
                <asp:Label ID="DirectionThreeLabel" runat="server" Text='<%# Eval("DirectionThree") %>' />
                <br />
                <asp:Label ID="DirectionFourLabel" runat="server" Text='<%# Eval("DirectionFour") %>' />
                <br />
                <br />
            </ItemTemplate>
        </asp:DataList>
    </asp:Panel>
    <asp:Button ID="btnPrintCurrent" runat="server" Text="Print Current Page" OnClick="PrintCurrentPage" />
   </div>
   <asp:HyperLink ID="HyperLink2" runat="server" NavigateUrl='<%# Bind("RecipeID",      "PageLinkDetails.aspx?RecipeId={0}") %>'
    Text='<%# Eval("Name") %>'>Rate This Recipe</asp:HyperLink>
  </asp:Content>



using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
 using System.Collections;
using System.Web;
 using System.Web.Security;
  using System.Web.UI;
  using System.Web.UI.WebControls;
 using System.Web.UI.WebControls.WebParts;
 using System.Web.UI.HtmlControls;
 using System.IO;
 using System.Text;
 using System.Web.SessionState;

namespace TestDataBase
{
public partial class PageLinkDetails : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        BindGrid();
    }

    private void BindGrid()
    {
        string strQuery = "select * " + "from CaribbeanDirections";
        DataTable dt = new DataTable();
        String strConnString = System.Configuration.ConfigurationManager
                    .ConnectionStrings["Caribbean"].ConnectionString;
        SqlConnection con = new SqlConnection(strConnString);
        SqlDataAdapter sda = new SqlDataAdapter();
        SqlCommand cmd = new SqlCommand(strQuery);
        cmd.CommandType = CommandType.Text;
        cmd.Connection = con;
        try
        {
            con.Open();
            sda.SelectCommand = cmd;
            sda.Fill(dt);
            //*DataList1.DataSource = dt;
            DataList1.DataBind();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            con.Close();
            sda.Dispose();
            con.Dispose();
        }
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        /*Verifies that the control is rendered */
    }

    protected void OnPaging(object sender, PageEventArgs e)
    {

        DataList1.DataBind();
    }

    protected void PrintCurrentPage(object sender, EventArgs e)
    {

        DataList1.DataBind();
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        DataList1.RenderControl(hw);
        string gridHTML = sw.ToString().Replace("\"", "'")
            .Replace(System.Environment.NewLine, "");
        StringBuilder sb = new StringBuilder();
        sb.Append("<script type = 'text/javascript'>");
        sb.Append("window.onload = new function(){");
        sb.Append("var printWin = window.open('', '', 'left=0");
        sb.Append(",top=0,width=1000,height=600,status=0');");
        sb.Append("printWin.document.write(\"");
        sb.Append(gridHTML);
        sb.Append("\");");
        sb.Append("printWin.document.close();");
        sb.Append("printWin.focus();");
        sb.Append("printWin.print();");
        sb.Append("printWin.close();};");
        sb.Append("</script>");
        ClientScript.RegisterStartupScript(this.GetType(), "GridPrint", sb.ToString());

        DataList1.DataBind();
    }

    protected void btnPrint_Click(object sender, EventArgs e)
    {
        Session["ctrl"] = pnl1;

    }
}
}

Upvotes: 4

Views: 39558

Answers (2)

Afzaal Ahmad Zeeshan
Afzaal Ahmad Zeeshan

Reputation: 15860

This might be a very late answer, but for the new users who might come to this post like me, I want them to know that they can easily print the page using CTRL + P (PRINT COMMAND). To print just a few elements you can add the classname or id. Have a look as below:

Printing the page

To print the page, simply press the Print Command on any browser. Or simply use the JS command

window.print();

You can keep this inside an event or anyother thing that you might want to be used such as a button:

<input type="button" value="Print" id="print" onclick="print()" />

function print() {
  window.print();
}

Printing only a part

Now that we have CSS3 in our hand, we can easily snip out the part we want to be printed. Here is example:

@media print {
   /* properties for printed page */
}

Any of the property you declare here would be applied to the document while its in hard copy (printed form). If you want to hide the footer or other divs, you can set them to invisible as

@media print {
  footer, header, non-printable-part {
    display: none;
  }
}

Now, when you send the print command or click the button. You're gonna see only the printable part. It has been made easy using CSS3 Media Query.

Upvotes: 2

Cherian M Paul
Cherian M Paul

Reputation: 656

If you want to print only a Datalist from a webpage. You can create a Div Name around the datalist and use the below code

<script language="javascript">
    function printDiv(divName) {
        var printContents = document.getElementById(divName).innerHTML;
        var originalContents = document.body.innerHTML;

        document.body.innerHTML = printContents;

        window.print();

        document.body.innerHTML = originalContents;
    }
</script>

Give a div name around the Datalist like this.

<div id="PrintDiv">
       <asp:DataList ID="DataList1" runat="server">     </asp:DataList>
</div>

Finally Create a print button.

<input type="button" onclick="printDiv('PrintDiv')" value="Print only Datalist!" />

EDIT

Your exact code worked for me. I created a ASP.NET website (Not Project). I copied your entire code and pasted into a new page and it worked.

The only thing I changed is the following.

I changed CodeBehind="PageLinkDetails.aspx.cs" to CodeFile="PageLinkDetails.aspx.cs"

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
 CodeFile="PageLinkDetails.aspx.cs" Inherits="TestDataBase.PageLinkDetails" %>

EDIT

Here is my Complete Code.

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
 CodeFile="PageLinkDetails.aspx.cs" Inherits="TestDataBase.PageLinkDetails" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <div>
    <asp:Panel ID="pnl1" runat="server">
        <asp:SqlDataSource runat="server" ID="SqlDataSource1" ConnectionString="<%$ ConnectionStrings:Database %>"

            SelectCommand="SELECT first AS Name, uid AS Id FROM users WHERE (uid IN (250, 251, 253, 252, 254))">
        </asp:SqlDataSource>
        <asp:DataList ID="DataList1" runat="server" DataKeyField="Id" DataSourceID="SqlDataSource1">
            <ItemTemplate>
                <asp:Label ID="NameLabel" runat="server" Text='<%# Eval("Name") %>' />
                <br />
                <br />
                INGREDIENTS:<br />
                <asp:Label ID="IngredientOneLabel" runat="server" Text='<%# Eval("Id") %>' />
                <br />
                <asp:Label ID="IngredientTwoLabel" runat="server" Text='<%# Eval("Id") %>' />
                <br />
                <asp:Label ID="IngredientThreeLabel" runat="server" Text='<%# Eval("Id") %>' />
                <br />
                <asp:Label ID="IngredientFourLabel" runat="server" Text='<%# Eval("Id") %>' />
                <br />
                <asp:Label ID="IngredientFiveLabel" runat="server" Text='<%# Eval("Id") %>' />
                <br />
                <asp:Label ID="IngredientSixLabel" runat="server" Text='<%# Eval("Id") %>' />
                <br />
                <asp:Label ID="IngredientSevenLabel" runat="server" Text='<%# Eval("Id") %>' />
                <br />
                <asp:Label ID="IngredientEightLabel" runat="server" Text='<%# Eval("Id") %>' />
                <br />
                <asp:Label ID="IngredientNineLabel" runat="server" Text='<%# Eval("Id") %>' />
                <br />
                <asp:Label ID="IngredientTenLabel" runat="server" Text='<%# Eval("Id") %>' />
                <br />
                Directions:<br />
                <asp:Label ID="DirectionOneLabel" runat="server" Text='<%# Eval("Id") %>' />
                <br />
                <asp:Label ID="DirectionTwoLabel" runat="server" Text='<%# Eval("Id") %>' />
                <br />
                <asp:Label ID="DirectionThreeLabel" runat="server" Text='<%# Eval("Id") %>' />
                <br />
                <asp:Label ID="DirectionFourLabel" runat="server" Text='<%# Eval("Id") %>' />
                <br />
                <br />
            </ItemTemplate>
        </asp:DataList>
    </asp:Panel>
    <asp:Button ID="btnPrintCurrent" runat="server" Text="Print Current Page" OnClick="PrintCurrentPage" />
   </div>
   <asp:HyperLink ID="HyperLink2" runat="server" NavigateUrl='<%# Bind("Id",      "PageLinkDetails.aspx?RecipeId={0}") %>'
    Text='<%# Eval("Name") %>'>Rate This Recipe</asp:HyperLink>
  </asp:Content>

This is code for aspx.cs

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
using System.Web.SessionState;

namespace TestDataBase
{
    public partial class PageLinkDetails : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            BindGrid();
        }

        private void BindGrid()
        {
            string strQuery = "SELECT first AS Name, uid AS Id FROM users WHERE (uid IN (250, 251, 253, 252, 254))";
            DataTable dt = new DataTable();
            String strConnString = System.Configuration.ConfigurationManager
                        .ConnectionStrings["Database"].ConnectionString;
            SqlConnection con = new SqlConnection(strConnString);
            SqlDataAdapter sda = new SqlDataAdapter();
            SqlCommand cmd = new SqlCommand(strQuery);
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            try
            {
                con.Open();
                sda.SelectCommand = cmd;
                sda.Fill(dt);
                //*DataList1.DataSource = dt;
                DataList1.DataBind();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                con.Close();
                sda.Dispose();
                con.Dispose();
            }
        }
        public override void VerifyRenderingInServerForm(Control control)
        {
            /*Verifies that the control is rendered */
        }

        protected void OnPaging(object sender, PageEventArgs e)
        {

            DataList1.DataBind();
        }

        protected void PrintCurrentPage(object sender, EventArgs e)
        {

            DataList1.DataBind();
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            DataList1.RenderControl(hw);
            string gridHTML = sw.ToString().Replace("\"", "'")
                .Replace(System.Environment.NewLine, "");
            StringBuilder sb = new StringBuilder();
            sb.Append("<script type = 'text/javascript'>");
            sb.Append("window.onload = new function(){");
            sb.Append("var printWin = window.open('', '', 'left=0");
            sb.Append(",top=0,width=1000,height=600,status=0');");
            sb.Append("printWin.document.write(\"");
            sb.Append(gridHTML);
            sb.Append("\");");
            sb.Append("printWin.document.close();");
            sb.Append("printWin.focus();");
            sb.Append("printWin.print();");
            sb.Append("printWin.close();};");
            sb.Append("</script>");
            ClientScript.RegisterStartupScript(this.GetType(), "GridPrint", sb.ToString());

            DataList1.DataBind();
        }

        protected void btnPrint_Click(object sender, EventArgs e)
        {
            Session["ctrl"] = pnl1;

        }
    }
}

Upvotes: 6

Related Questions