2013-04-06 57 views
-1

我已經設置了一個窗體,其中我有一個DataGridView的預訂,目前我可以打印DataGridView但只顯示內容,因此只有通過向下滾動才能看到的數據不會打印。打印DataGridView

如何更改我的代碼,因此當我單擊打印按鈕時,所有內容(包括通過滾動查看的數據)都會打印到頁面上?

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

namespace project 
{ 
    public partial class frmViewBookings : Form 
    { 
     public frmViewBookings() 
     { 
      InitializeComponent(); 
     } 

     private void btnClose_Click(object sender, EventArgs e) 
     { 
      Form3 mainpage = new Form3(); 
      mainpage.Show(); 
      this.Close(); 
     } 

     private void frmViewBookings_Load(object sender, EventArgs e) 
     { 
      // TODO: This line of code loads data into the 'usersDataSet1.Booking' table. You can move, or remove it, as needed. 
      this.bookingTableAdapter.Fill(this.usersDataSet1.Booking);  
     } 

     private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) 
     { 
      Bitmap bm = new Bitmap(this.dataGridView1.Width, this.dataGridView1.Height); 
      this.dataGridView1.DrawToBitmap(bm, new Rectangle(0, 0, this.dataGridView1.Width, this.dataGridView1.Height)); 
      e.Graphics.DrawImage(bm, 0, 0); 
     } 

     private void btnPrint_Click(object sender, EventArgs e) 
     { 
      printDocument1.Print(); 
     } 
    } 
} 
+0

爲什麼不使用報告? – Obama 2013-04-06 21:48:48

+0

嗯好主意,我會嘗試報告,如果我不能這樣做。我是新手,所以需要閱讀報告。有什麼建議麼? – bandaa 2013-04-06 21:49:58

+1

我想做同樣的事情,但我結束了使用微軟報告。它並不難。你必須爲你的DataGridView數據源創建一個類(如果你沒有的話)。然後,在報告中,您將創建一個帶有該類的DataSet的Tablix。最後,在運行時,將DataGridView中的DataSource列表作爲參數傳遞給報表,並且完成。如果你想這樣做,告訴我,我可以給你一個代碼示例。 – Andres 2013-04-06 23:27:32

回答

1

你所要做的就是創建一個虛擬的形式,這就是你要打印則控制添加到虛擬形式和表現形式,並打印在虛擬控制控件的大小。

這是我如何做的:

private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) 
{ 
    //Create bitmap 
    Bitmap image = new Bitmap(dataGridView1.Width, dataGridView1.Height); 
    //Create form 
    Form f = new Form(); 
    //add datagridview to the form 
    f.Controls.Add(dataGridView1); 
    //set the size of the form to the size of the datagridview 
    f.Size = dataGridView1.Size; 
    //draw the datagridview to the bitmap 
    dataGridView1.DrawToBitmap(image, new Rectangle(0, 0, dataGridView1.Width, dataGridView1.Height)); 
    //dispose the form 
    f.Dispose(); 
    //print 
    e.Graphics.DrawImage(image, 0, 0); 
}