Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print Datagrid records in WPF

Tags:

wpf

datagrid

I need to print datagrid records only. I used one code like this, but this one printed datagrid scroll bar also. I need only records.

PrintDialog printDlg = new PrintDialog();
printDlg.PrintVisual(grid1, "Grid Printing.");
like image 273
Lawrence Avatar asked May 14 '13 07:05

Lawrence


1 Answers

Hey For Print DataGrid in WPF you have to take <StackPanel> and use given code.

Xaml Code is

 <StackPanel>
        <DataGrid AutoGenerateColumns="False" Margin="12,0,0,0" Name="dataGrid1"  HorizontalAlignment="Left"  VerticalAlignment="Top"  ItemsSource="{Binding}" AlternatingRowBackground="LightGoldenrodYellow" AlternationCount="1">
            <DataGrid.Columns>
                <DataGridTemplateColumn Header="Image" Width="SizeToCells" IsReadOnly="True">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Image Source="{Binding Path=Image}" Width="100" Height="50" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>


                <DataGridTextColumn Header="Make" Binding="{Binding Path=Make}"/>
                <DataGridTextColumn Header="Model" Binding="{Binding Path=Model}"/>
                <DataGridTextColumn Header="Price" Binding="{Binding Path=Price}"/>
                <DataGridTextColumn Header="Color" Binding="{Binding Path=Color}"/>
            </DataGrid.Columns>
        </DataGrid>
        <Button Content="Print" Click="OnDataGridPrinting"  Width="80" Height="30" />
    </StackPanel>

And .CS code is

   private void OnDataGridPrinting(object sender, RoutedEventArgs e)
    {
        System.Windows.Controls.PrintDialog Printdlg = new System.Windows.Controls.PrintDialog();
        if ((bool)Printdlg.ShowDialog().GetValueOrDefault())
        {
            Size pageSize = new Size(Printdlg.PrintableAreaWidth, Printdlg.PrintableAreaHeight);
            // sizing of the element.
            dataGrid1.Measure(pageSize);
            dataGrid1.Arrange(new Rect(5, 5, pageSize.Width, pageSize.Height));
            Printdlg.PrintVisual(dataGrid1, Title);
        }
    }

Hope it helps you

This is tested code.

like image 136
Neeraj Dubey Avatar answered Sep 29 '22 23:09

Neeraj Dubey