New to Telerik UI for WinForms? Download free 30-day trial

How to print row numbers in RadPrintDocument

Environment

Product Version Product Author
2021.2.511 RadGridView for WinForms Nadya Karaivanova

Description

A client's requirement is to display row numbers in front of each row in RadGridView. This can be easily achieved in ViewCellFormatting event where you can sync the e.CellElement.Text to display the respective CellElement.RowIndex. However, when printing the grid using RadPrintDocument, this column is not automatically printed.

how-to-print-row-numbers-in-radprintdocument001

This tutorial will demonstrate how you can print the most left column in RadGridView containing row numbers.

Solution

Let's first set up our grid to display row numbers at the beginning of each row:

public RadForm1()
{
    InitializeComponent();
    this.radGridView1.DataSource = this.GetData();
    this.radGridView1.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill;
    this.radGridView1.ViewCellFormatting += RadGridView1_ViewCellFormatting;
    this.radGridView1.PrintCellPaint += RadGridView1_PrintCellPaint;
}

private void RadGridView1_ViewCellFormatting(object sender, CellFormattingEventArgs e)
{
    if (e.CellElement is GridRowHeaderCellElement && e.CellElement.RowIndex >= 0)
    {
        e.CellElement.Text = (e.CellElement.RowIndex + 1).ToString();
    }
}

Then, to print this column in the RadPrintDocument it is neccessary to handle the PrintCellPaint event and paint the necessary info. This event allow you to access the cell and to paint in it whatever you need.

private void RadGridView1_PrintCellPaint(object sender, PrintCellPaintEventArgs e)
{
    if (e.Row is GridViewDataRowInfo && e.Column.FieldName == "Name")
    {
        Rectangle rect = new Rectangle();
        rect.X = e.CellRect.X - 25;
        rect.Y = e.CellRect.Y;
        rect.Width = 25;
        rect.Height = e.CellRect.Height;
        StringFormat sf = new StringFormat();
        sf.LineAlignment = StringAlignment.Center;
        sf.Alignment = StringAlignment.Center;
        // Row index text
        e.Graphics.DrawString(e.Row.Index.ToString(), Control.DefaultFont, Brushes.Black, rect, sf);
        // Row index border
        e.Graphics.DrawRectangle(Pens.Black, rect);
    }
}

Thus, when printing the grid via the PrintButton_Click you should see the printed row numbers in the document:

private void PrintButton_Click(object sender, EventArgs e)
{
    RadPrintDocument doc = new RadPrintDocument();
    doc.AssociatedObject = this.radGridView1;
    doc.Print();
}

how-to-print-row-numbers-in-radprintdocument002

In this article