2

我花了 5 天时间研究如何在 C# Visual Studio 网站中打印 DataList。我可以在 Web 项目中打印 DataList。看来,由于站点不像项目那样具有“命名空间”,微软只是没有费心使网站页面可打印。我有一个比较大的网站快要开发出来了,现在看来一个网站的主要功能是不可能的。我需要帮助!提前致谢。

PS 微软似乎会在他们将项目与站点进行比较的文献中提到这个小问题,但他们没有。

<%@ 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;

    }
}
}
4

2 回答 2

4

如果您只想从网页打印数据列表。您可以围绕数据列表创建一个 Div 名称并使用以下代码

<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>

像这样在 Datalist 周围给一个 div 名称。

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

最后创建一个打印按钮。

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

编辑

您的确切代码对我有用。我创建了一个 ASP.NET 网站(不是项目)。我复制了你的整个代码并粘贴到一个新页面中,它可以工作。

我唯一改变的是以下内容。

CodeBehind="PageLinkDetails.aspx.cs"改为CodeFile="PageLinkDetails.aspx.cs"

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

编辑

这是我的完整代码。

<%@ 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>

这是 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;

        }
    }
}
于 2013-08-19T21:50:47.297 回答
1

这可能是一个很晚的答案,但对于像我这样可能来到这篇文章的新用户,我希望他们知道他们可以使用CTRL+ P(打印命令)轻松打印页面。要仅打印几个元素,您可以添加类名或 id。看看如下:

打印页面

要打印页面,只需在任何浏览器上按打印命令。或者干脆使用JS命令

window.print();

您可以将其保存在事件或您可能想要使用的任何其他东西中,例如按钮:

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

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

只打印一部分

现在我们手里有了 CSS3,我们可以很容易地剪掉我们想要打印的部分。这是示例:

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

您在此处声明的任何属性都将应用于硬拷贝(印刷形式)的文件。如果要隐藏页脚或其他 div,可以将它们设置为不可见

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

现在,当您发送打印命令或单击按钮时。你只会看到可打印的部分。使用 CSS3 Media Query 已经很容易了。

于 2014-04-06T12:47:29.390 回答