传递gridview名称进行打印

时间:2012-10-20 20:08:24

标签: c# asp.net gridview

我有一个打印网格的工作函数。我有很多网格。在下面的代码中,gridname是硬编码的(代码隐藏)。

当按下asp.net按钮时,我可以将gridview名称作为参数传递吗?

然后我可以使用一个打印函数来处理所有可扩展且非常棒的网格。

标记:

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

代码背后:

protected void PrintCurrentPage(object sender, EventArgs e) // Print Current Page
        {

            try
            {


                StringWriter sw = new StringWriter();
                HtmlTextWriter hw = new HtmlTextWriter(sw);
                GridViewErrorReport.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>");
                Page.ClientScript.RegisterStartupScript(this.GetType(), "GridPrint", sb.ToString());


            }

JavaScript的:

<script type="text/javascript">
    function PrintGridData() {
        var prtGrid = document.getElementById('<%=GridViewErrorReport.ClientID %>');
        prtGrid.border = 0;
        var prtwin = window.open('', 'PrintGridViewData', 'left=100,top=100,width=1000,height=1000,tollbar=0,scrollbars=1,status=0,resizable=1');
        prtwin.document.write(prtGrid.outerHTML);
        prtwin.document.close();
        prtwin.focus();
        prtwin.print();
        prtwin.close();
    }
</script>

1 个答案:

答案 0 :(得分:1)

是的,您可以将id传递给您的函数,并使用它从页面中检索您的网格控件。

假设“myGridId”传递给函数...

您的代码现在应该是这样的

StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridViewErrorReport.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(\"");
GridView gv = (GridView)this.FindControl("myGridId");
sb.Append(gv);
sb.Append("\");");
sb.Append("printWin.document.close();");
sb.Append("printWin.focus();");
sb.Append("printWin.print();");
sb.Append("printWin.close();};");
sb.Append("</script>");
Page.ClientScript.RegisterStartupScript(this.GetType(), "GridPrint", sb.ToString());