Search code examples
c#wpfprintingdatagridsystem.drawing

How to print a DataGrid in WPF, not a DataGridView


"InvokePaint" is displaying error, "this" of the InvokePaint method is supposed to be a class, but i don't know which class it should be, any help will be appreciated.

SqlDataAdapter da = new SqlDataAdapter("Select * from CallRegister", data.getCon());
                DataTable dt = new DataTable("Call Reciept");
                da.Fill(dt);
                DataGrid dg = new DataGrid();
                dg.ItemsSource = dt.DefaultView;
                System.Drawing.Size m = new System.Drawing.Size((int)dg.Width, (int)dg.Height);

                System.Windows.Forms.PaintEventArgs myPaintArgs = new System.Windows.Forms.PaintEventArgs(e.Graphics, new System.Drawing.Rectangle(new System.Drawing.Point(0, 0),m));
                this.InvokePaint(dg, myPaintArgs);

Solution

  • This method can be called only from WindowsForms control as MSDN says:

    Raises the Paint event for the specified control. Namespace:
    System.Windows.Forms Assembly: System.Windows.Forms (in System.Windows.Forms.dll)

    So this code should be called from hosted WinForms control inside WPF project:

    this.InvokePaint((dg, myPaintArgs); 
    

    Update. To print Datagrid:

    XAML:

    <DataGrid  ItemsSource="{Binding Path=Persons, Mode=TwoWay}" Name="dataGrid"/>
    <Button Grid.Row="1" Click="Button_Click" Content="Print DataGrid"/>
    

    Code behind:

    private void Button_Click(object sender, RoutedEventArgs e)
    {            
       var pd = new PrintDialog();
       var result = pd.ShowDialog();
       if (result.HasValue && result.Value)
          pd.PrintVisual(dataGrid, "My WPF printing a DataGrid");
    }