Click here to Skip to main content
15,886,789 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I want to print data from datagridview. My code is working fine, but when it prints the data my application crashes. And I have to start application again. I have tried to catch exception with try catch block but there is no exception

I want two things

Set data from datagridview so that I don't have to use multiple \n and \t

After printing data application don't crash and it show the same form again. My code is




private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{

    try
    {




        Graphics graphic = e.Graphics;
        Font font = new Font("Courier New", 12);

        float fontHieght = font.GetHeight();
        int startX = 12;
        int startY = 12;
        int offset = 40;
         graphic.DrawString("\t  Shop Name \n \t  Address \n \t  Phone Number\n",new Font("Courier New", 12),new SolidBrush(Color.Black), startX,startY);

          string underline= "\t \n \n\n --------------------------------------\n" ;

         graphic.DrawString(underline, new Font("Courier New", 12), new SolidBrush(Color.Black), startX, startY + offset);

        int noOfRows = dataGridView1.Rows.Count;
        string a =  dataGridView1.Rows[0].Cells[0].Value.ToString();
        string cusname = "\n\n\n\nCustomer Name:\t " + a+"\n";
        graphic.DrawString(cusname, new Font("Courier New", 12), new SolidBrush(Color.Black), startX, startY + offset);
        string headings = "\t\n \n\n\n\n\n\n\n Item Name\t Price \t Quantity \t Total \n ";  
        graphic.DrawString(headings, new Font("Courier New", 12), new SolidBrush(Color.Black), startX, startY + offset);


        for (int i = 0; i < noOfRows - 1; i++)
       {



            DataGridViewRow row = dataGridView1.Rows[i];


            string b = row.Cells[2].Value.ToString();
            string c = "\t" + row.Cells[3].Value.ToString();
            string d = "\t" + row.Cells[4].Value.ToString();
            string f = "\t" + row.Cells[5].Value.ToString();
            string g = "\n\n\n\n\n\n\n\n \n\n"  + b + "\t" + c + "\t" + d + "\t" + f + "\t"+"\n";
            graphic.DrawString(g, new Font("Courier New", 12), new SolidBrush(Color.Black), startX, startY + offset);
             offset = offset + 20;

        }

        graphic.DrawString("\t\n\n\n\t\n\n\n\t\n\n\n\nSoftware by Softcare\n", new Font("Courier New", 12), new SolidBrush(Color.Black), startX, startY + offset);


    }

    catch (Exception ex)
    {

        MessageBox.Show("Error is : "+ex);
    }



}


Copied from comment:
I figured out where the problem was, It was in Login form's login button.
When I remove the connection.close() and connection.dispose()then print part works But I don't know why its the cause.

Login code is:
C#
private void login_button_Click(object sender, EventArgs e)
{
    connection.Open();

    OleDbCommand command = new OleDbCommand();
    command.Connection = connection;
    command.CommandText = "Select * from Login where Username='" + username_text.Text+ "' and Pass='"+ pass_text.Text+"' ";
    OleDbDataReader reader = command.ExecuteReader();
    int count = 0;
    while (reader.Read())
    {
        count++;
    }

    if (count == 1)
    {
        MessageBox.Show("Username and Password are Correct");
        connection.Close();
        connection.Dispose();
        this.Hide();
        Main_Form mf = new Main_Form();
        mf.ShowDialog();
        this.Close();
    }
    else if (count > 1)
    {
        MessageBox.Show("Dublicate Username and Password ");
        connection.Close();
    }
    else
    {
        MessageBox.Show("Username and Password are not Correct");
        connection.Close();
    }
}
Posted
Updated 22-Apr-15 9:06am
v2
Comments
Richard MacCutchan 19-Apr-15 13:14pm    
If there is no exception, then you need to explain exactly what happens.

It is quite possibly something to do with you consuming all those resources. Create a single Font and Brush at the beginning and use them throughout. Do not keep creating new ones for every graphics call.

1 solution

I pasted your code into a new Windows-Forms-Project, added a DataGridView and a PrintDocument to the Form and it worked for me. The only issue I had was that initially my DataGridView had less than six columns, so I got an exception where the row-cells are being accessed. So I would suggest you double-check that. If your DataGridView does have 6 or more columns, then the cause for trouble must be somewhere outside your posted code.

Apart from that, you should use graphics objects (like Font and SolidBrush) in a using-Block (because they're IDisposable[^]) and re-use that one instance wherever needed. I did that for you here - it should be ready as a drop-in replacement for your code:
C#
private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
    try
    {
        Graphics graphic = e.Graphics;

        using (Font courier12 = new Font("Courier New", 12))
        using (SolidBrush blackBrush = new SolidBrush(Color.Black))
        {
            int startX = 12;
            int startY = 12;
            int offset = 40;
            graphic.DrawString("\t  Shop Name \n \t  Address \n \t  Phone Number\n", courier12, blackBrush, startX, startY);

            string underline = "\t \n \n\n --------------------------------------\n";

            graphic.DrawString(underline, courier12, blackBrush, startX, startY + offset);

            int noOfRows = dataGridView1.Rows.Count;
            string a = dataGridView1.Rows[0].Cells[0].Value.ToString();
            string cusname = "\n\n\n\nCustomer Name:\t " + a + "\n";
            graphic.DrawString(cusname, courier12, blackBrush, startX, startY + offset);
            string headings = "\t\n \n\n\n\n\n\n\n Item Name\t Price \t Quantity \t Total \n ";
            graphic.DrawString(headings, courier12, blackBrush, startX, startY + offset);

            for (int i = 0; i < noOfRows - 1; i++)
            {
                DataGridViewRow row = dataGridView1.Rows[i];

                string b = row.Cells[2].Value.ToString();
                string c = "\t" + row.Cells[3].Value.ToString();
                string d = "\t" + row.Cells[4].Value.ToString();
                string f = "\t" + row.Cells[5].Value.ToString();
                string g = "\n\n\n\n\n\n\n\n \n\n" + b + "\t" + c + "\t" + d + "\t" + f + "\t" + "\n";
                graphic.DrawString(g, courier12, blackBrush, startX, startY + offset);
                offset = offset + 20;
            }

            graphic.DrawString("\t\n\n\n\t\n\n\n\t\n\n\n\nSoftware by Softcare\n", courier12, blackBrush, startX, startY + offset);
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error is : " + ex);
    }
}


Edit after comments:

It's not completely obvious to me how this is causing the issue, but:

Disposable objects (e.g. DbConnection, DbCommand, DbDataReader, Form) should always be properly disposed when they go out of scope (when you stop using them). Not doing this can have all sorts of strange effects and somehow this fired back on you here.

This Google-query shows you several articles here on CodeProject that explain what IDisposable is about and how it's properly dealt with. Have a look at one or two to get the idea:
https://www.google.com/search?q=idisposable+codeproject&ie=utf-8&oe=utf-8[^]

There would be more ways to deal with this but the simplest one would be to not declare your connection-object as a class member but to create (and dispose) it in the method where you use it, like so:
C#
private void login_button_Click(object sender, EventArgs e)
{
    using (var connection = new OleDbConnection(/*insert connection string variable here*/))
    using (var command = new OleDbCommand())
    {
        command.Connection = connection;
        command.CommandText = "Select * from Login where Username='" + username_text.Text+ "' and Pass='"+ pass_text.Text+"' ";
        using (var reader = command.ExecuteReader())
        {
            int count = 0;
            while (reader.Read())
            {
                count++;
            }
        } // reader gets closed and disposed here
    } // command and connection get closed and disposed here
 
    if (count == 1)
    {
        MessageBox.Show("Username and Password are Correct");
        this.Hide();
        Main_Form mf = new Main_Form();
        mf.ShowDialog();
        this.Close();
    }
    else if (count > 1)
    {
        MessageBox.Show("Dublicate Username and Password ");
    }
    else
    {
        MessageBox.Show("Username and Password are not Correct");
    }
}


Also I would strongly suggest you to use SQL-Parameters instead of concatenating your query-criteria into the query-string. Here's a good example: http://www.dotnetperls.com/sqlparameter[^]
 
Share this answer
 
v5
Comments
mr92furqan 20-Apr-15 5:57am    
I have tried you code, and checked without using data Grid View and print random data. It still crashed after print.
Sascha Lefèvre 20-Apr-15 6:03am    
I would suggest:
- Try it with a different printer (for simplicity, just declare another printer as the default one. If you don't have another printer available, you could install a PDF-Printer, e.g. http://freepdfxp.de )
- Try it with completely dumbed down print output - just printing a single line of text.
- If all that fails, try the code sample from this page in a new project:
https://msdn.microsoft.com/en-us/library/system.drawing.printing.printdocument%28v=vs.110%29.aspx

Maybe that will lead to a clue.
mr92furqan 22-Apr-15 13:06pm    
I have tried all of your suggestions.
1- When I tried to create a new project and print a simple line, it worked.
but when i used same code in my project it crashed.I changed the form and pasted same code there. My application crashed again.
I don't understand whats the matter.
Sascha Lefèvre 22-Apr-15 13:22pm    
Alright, new suggestion :)

Make a copy of your solution-directory. Open the copied solution, throw everything out except that single form and try again.

If it works, the problem is somehow related to your other code. In that case, start over with a new copy of the solution and throw out the other code bit by bit while re-trying to print in order to figure out which part of your code is causing trouble.

If it still doesn't work, I would guess it's related to some project-setting (though I wouldn't know of one which could cause this). In that case, compare your project settings to that of the sample-code-project.
mr92furqan 22-Apr-15 13:35pm    
Ok thanks I am trying.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900