John Ernest Guadalupe
John Ernest Guadalupe

Reputation: 6629

Why does my code open two Microsoft Office Word instances?

I use a function to ease printing in my application. Here it is:

public void print(string fileName, string variables, string values, string template)
        {
            // CREATE TEXT FILE FOR PRINTING


        FileInfo fi = new FileInfo(fileName);
        Object oMissing = System.Reflection.Missing.Value;
        Object oTrue = true;
        Object oFalse = false;

        Word.Application _wordApp = new Word.Application();
        Word.Document oDoc = _wordApp.Documents.Add(template);

        try
        {
            // Check if file already exists. If yes, delete it. 
            if (fi.Exists)
            {
                fi.Delete();
            }

            // Create a new file 
            using (StreamWriter sw = fi.CreateText())
            {
                sw.WriteLine(variables);
                sw.WriteLine(values);
            }


            _wordApp.Visible = true;
            oDoc.MailMerge.MainDocumentType = Word.WdMailMergeMainDocType.wdFormLetters;
            oDoc.MailMerge.OpenDataSource(fileName, false, false, true);

            oDoc.MailMerge.Destination = Word.WdMailMergeDestination.wdSendToNewDocument;
            oDoc.MailMerge.Execute(false);
            oDoc.MailMerge.Application.PrintOut();
        }
        catch (Exception Ex)
        {
            MessageBox.Show(Ex.ToString());
        }
        finally
        {
            //CLEAR RESOURCES
            ((Word._Document)oDoc).Close(ref oFalse, ref oMissing, ref oMissing);
            ((Word._Application)_wordApp).Quit();
        }

    }

It looks fine since I can use Mail Merge and make things easier. I open an Open File Dialog so the user can pick the template file that he will use for Mail Merge. But then, the application opens the template file without any data on the Merge Fields and then performs the Mail Merge opening another Document with all the Merge Fields filled in.

Any ideas why this happens? Here is the code for the Open File Dialog:

                //CHOOSE TEMPLATE FILE
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Filter = "Microsoft Word Template (*.dotx)|*.dotx";
                string filter = ofd.Filter;
                ofd.Multiselect = false;
                ofd.Title = "Open Template File";
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    if (ofd.SafeFileName == "payslip.dotx")
                    {
                        //RETREIVE VALUES
                        var db = new DBConnect();
                        string[] values = new string[20];
                        bool print = false;
                        OleDbCommand cmd = null;
                        OleDbDataReader dr = null;
                        try
                        {
                            if (db.OpenConnection() == true)
                            {
                                string query = "SELECT * FROM employee WHERE employee_ID = " + idTxtBox.Text + "";
                                cmd = new OleDbCommand(query, db.mycon);
                                dr = cmd.ExecuteReader();
                                while (dr.Read())
                                {
                                    values[2] = (dr["employeeName"].ToString());
                                    values[3] = (dr["withTax"].ToString());
                                    values[4] = (dr["sss"].ToString());
                                    values[5] = (dr["pagIbig"].ToString());
                                    values[6] = (dr["pHealthGov"].ToString());
                                    values[7] = (dr["pCareOff"].ToString());
                                    values[8] = (dr["loan_sss"].ToString());
                                    values[9] = (dr["loan_pagIbig"].ToString());
                                    values[10] = (dr["loan_koti"].ToString());
                                    values[11] = (dr["tardinessAbscences"].ToString());
                                    values[12] = totalDeductionsTxtBox.Text;
                                    values[13] = (dr["overTime"].ToString());
                                    values[14] = (dr["leave"].ToString());
                                }
                                print = true;
                            }
                        }
                        catch (OleDbException ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
                        finally
                        {
                            if (dr.IsClosed == false)
                            {
                                dr.Close();
                            }
                            db.CloseConnnection();
                        }

                        if (print == true)
                        {
                            // PRINTING
                            var p = new printClass();
                            p.print(@"C:\IT Box Incorporated\Payroll\payslipCSV.csv",
                                    "date_issued,employee_name,tax,sss,pagibig,phg,pco,sssloan,pagibigloan,kotiloan,late,total,ot,leave",
                                    "" + (DateTime.Now.Date.ToString("MMM") + " " + DateTime.Now.Date.ToString("yyyy")) + "," + values[2] + "," + values[3] + "," + values[4] + "," + values[5] + "," + values[6] + "," + values[7] + "," + values[8] + "," + values[9] + "," + values[10] + "," + values[11] + "," + values[12] + "," + values[13] + "," + values[14] + "",
                                    ofd.FileName);
                        }
                        else
                        {
                            MessageBox.Show("Print Failed!");
                        }
                    }
                    else
                    {
                        MessageBox.Show("Print Failed! Wrong File!");
                    }
                }
                else
                {
                    MessageBox.Show("Print Failed!");
                }

Upvotes: 1

Views: 473

Answers (1)

Kiru
Kiru

Reputation: 3565

In Windows 7 if you have preview enabled then during the file open Windows will try to preview a document and starts a new winword process.

Disable the preview mode in Windows 7.

Upvotes: 1

Related Questions