'Printing Datagrid view in C# in windows form application

I am facing a problem while doing a project in C# of Inventory management system. Here I have to print some datagrid view with PRINT button by a printer. I am facing problem while printing the datagridView. I had the code i am giving below. Can you please modify the code to print a datagridview with testing with a printer.

Here's my code :

private void Print_Click(object sender, EventArgs e)
    {

        try
        {
            PrintDocument pd = new PrintDocument();
            pd.DefaultPageSettings.PaperSize = new PaperSize("A4", 827, 1170); // all sizes are converted from mm to inches & then multiplied by 100.
            pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
            //pd.PrinterSettings = PrinterSettings.InstalledPrinters.
            pd.Print();
        }
        catch (Exception ex)
        {
            MessageBox.Show("An error occurred while printing", ex.ToString());
        }
    }
    private void pd_PrintPage(object sender, PrintPageEventArgs ev)
    {
        if (t < 1)
        {
            ev.Graphics.DrawString(dataGridView1., new Font("Times New Roman", 14, FontStyle.Bold), Brushes.Black, 20, 225);
            t++;
            if (t < 1)
            {
                ev.HasMorePages = true;
            }
            else
            {
                ev.HasMorePages = false;
            }
        }
    }


Solution 1:[1]

This might help:

I'm not that advanced with printing but I used a PrintDialog like this:

    private void PrintDoc()
    {
        PrintDialog printDialog = new PrintDialog(); //make a printDialog object

        PrintDocument printDocument = new PrintDocument(); // make a print doc object

        printDialog.Document = printDocument; //document for printing is printDocument

        printDocument.PrintPage += printDocument_PrintPage; //event handler fire



        DialogResult result = printDialog.ShowDialog();
        if (result == DialogResult.OK)
        {
            printDocument.Print();
        }

    }

If that doesn't help, according to you error and your code I'm not sure if the index it is talking about comes from the dataGridView or from the ev.graphics, but I think you are missing some code?

private void printDocument_PrintPage(object sender, PrintPageEventArgs ev)
{
    Graphics graphic = ev.Graphics;
    foreach (DataRow row in dataGridView1.Rows)
        {
            string text = row.ToString() //or whatever you want from the current row
            graphic.DrawString(text,new Font("Times New Roman", 14, FontStyle.Bold), Brushes.Black, 20, 225);
        }
}

Solution 2:[2]

If you want the simplest way to print. try this: link

you also can use this for more functionality.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CularBytes
Solution 2 Al Masum Fahim