2012-10-20 67 views
0

我有一個打印網格的工作函數。我有很多網格。在下面的代碼中,網格名稱是硬編碼的(後面的代碼)。傳遞gridview名稱用於打印

當按下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

是的,它是可能的,你可以通過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()); 
+0

正確。謝謝。 – user1438082