Click here to Skip to main content
15,907,395 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Print button is working in source code but not working in exe file c#.net 2010 windows forms.

What is the reason could be? any help will be appreciated.
And below is the full code.

C#
private void Form1_Load(object sender, EventArgs e)
        {

            PayMthodCombo.SelectedItem = PayMthodCombo.Items[0];
            this.reportViewer1.RefreshReport();
            userNameTxt.Text = value;
        }

        private void printBtn_Click(object sender, EventArgs e)
        {
            string sql = "select * from invoicesview where voucherNo = "+ voucherNoTxt.Text +"";
            var dt = GetDataTable(sql);
            LocalReport report = new LocalReport();
            string path = Path.GetDirectoryName(Application.ExecutablePath);
            string fullPath = Path.GetDirectoryName(Application.ExecutablePath).Remove(path.Length - 10) + @"\Report\rptProductMemo.rdlc";
            report.ReportPath = fullPath;
            report.DataSources.Add(new ReportDataSource("dsProduct", dt));
            int printQty = Convert.ToInt32(voucherNoTxt.Text);

                PrintToPrinter(report);
           

        }

        public DataTable GetDataTable(string sql)
        {
            try
            {
                var dt = new DataTable();
                cls.conn.Open();
                SqlDataAdapter adpt = new SqlDataAdapter(sql, cls.conn);
                adpt.Fill(dt);
                cls.conn.Close();
                return dt;
            }

            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public static void PrintToPrinter(LocalReport report)
        {
            Export(report);

        }

        public static void Export(LocalReport report, bool print = true)
        {
            string deviceInfo =
             @"<deviceinfo>
                <outputformat>EMF
                <pagewidth>3in
                <pageheight>8.3in
                <margintop>0in
                <marginleft>0.1in
                <marginright>0.1in
                <marginbottom>0in
            ";
            Warning[] warnings;
            m_streams = new List<stream>();
            report.Render("Image", deviceInfo, CreateStream, out warnings);
            foreach (Stream stream in m_streams)
                stream.Position = 0;

            if (print)
            {
                Print();
            }
        }


        public static void Print()
        {
            if (m_streams == null || m_streams.Count == 0)
                throw new Exception("Error: no stream to print.");
            PrintDocument printDoc = new PrintDocument();
            if (!printDoc.PrinterSettings.IsValid)
            {
                throw new Exception("Error: cannot find the default printer.");
            }
            else
            {
                printDoc.PrintPage += new PrintPageEventHandler(PrintPage);
                m_currentPageIndex = 0;
                printDoc.Print();
            }
        }


What I have tried:

I did not try any thing yet, i can not debug it because it has no problem when i print from the source code.
Posted
Updated 14-May-24 10:25am
v2
Comments
Maciej Los 14-May-24 16:26pm    
What is error message?
ABAKh 14-May-24 16:42pm    
An error occurred during local report processing.
ABAKh 14-May-24 16:35pm    
Unhandled exception has occurred in your application. If you click .....

An error occurred during local report processing.
Dave Kreskowiak 14-May-24 16:58pm    
You are ALWAYS creating and running an executable. Just because you run the code from inside Visual Studio does not mean VS is running the code. VS will compile the code into an executable, run it, then attach the debugger to that running instance.
ABAKh 14-May-24 17:14pm    
More explanation please.

1 solution

As Dave has said, you always run an executable - the difference I think you are meeting is "Development" vs "Production" code - the former executes within the Visual Studio Debugger, and the latter directly from an EXE file.

Which means that it's likely that it's your DB connection that is wrong - and we can't see that code, it's hidden behind your "cls.conn" which we have no access to.
But a good guess would be that you have the wrong connection string, or that a previous operation failed and left the connection open so the attempt to open it again failed.

Start by thinking about why you add a try ... catch block: it's pretty much useless if all you ever do is re-throw the exception and discard possibly useful info - a finally block to ensure the connection is closed and maybe some logging in the catch block so you can conduct a post-mortem examination of the error causes would probably help as well.

But you have bigger problems: Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Always use Parameterized queries instead.

When you concatenate strings, you cause problems because SQL receives commands like:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'
The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;--'
Which SQL sees as three separate commands:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';
A perfectly valid SELECT
SQL
DROP TABLE MyTable;
A perfectly valid "delete the table" command
SQL
--'
And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.

So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?
 
Share this answer
 
Comments
ABAKh 15-May-24 15:54pm    
Thank you and I appreciate your assistance,
I added this code (if (cls.conn.State == ConnectionState.Open) { cls.conn.Close(); }) to ensure that the connection is closed.
And even I created and installed the file in the development server but still same error has been raised.

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