Click here to Skip to main content
15,846,977 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to fill out parental consent forms for four people using the word automation method on each page by pulling data from the database. I think there is an error in the loop in my codes. I am getting one student's parental consent form on each page. I couldn't solve it.

What I have tried:

C#
private void VelizinBelDok()
{
    try
    {
        System.Threading.Thread.Sleep(100);
        Cursor.Current = Cursors.WaitCursor;

        int iTotalFields = 1;
        Object oMissing = System.Reflection.Missing.Value;
        Object oTrue = true;
        Object oFalse = false;
        Word.Application oWord = new Word.Application();
        Word.Document oWordDoc = new Word.Document();
        oWord.Visible = true;
        oWord.WindowState = Word.WdWindowState.wdWindowStateMinimize;
        oWord.WindowState = Word.WdWindowState.wdWindowStateMaximize;
        Object oTemplatePath = System.Windows.Forms.Application.StartupPath + "\\Belgeler\\VelizinBel.docx";

        using (var conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source = gezievrak2541.accdb; Jet OLEDB:Database Password = Fatih2541; Mode = ReadWrite"))
        {
            conn.Open();

            using (var cmd = new OleDbCommand("Select * from gezilistemiz25,gezibilgileri25 WHERE unvani='Öğrenci'", conn))
            {
                using (OleDbDataReader dr = cmd.ExecuteReader())
                {
                    if (dr.HasRows)
                    {
                        while (dr.Read())
                        {
                            oWordDoc = oWord.Documents.Add(ref oTemplatePath, 
                               ref oMissing, ref oMissing, ref oMissing);

                            foreach (Word.Field myMergeField in oWordDoc.Fields)
                            {
                                iTotalFields++;
                                Word.Range rngFieldCode = myMergeField.Code;
                                String fieldText = rngFieldCode.Text;

                                if (fieldText.StartsWith(" MERGEFIELD"))
                                {
                                    Int32 endMerge = fieldText.IndexOf("\\");
                                    Int32 fieldNameLength = fieldText.Length - endMerge;
                                    String fieldName = fieldText.Substring(11, endMerge - 11);
                                    fieldName = fieldName.Trim();                                     

                                    if (fieldName == "sinifi")
                                    {
                                        myMergeField.Select();
                                        
                            oWord.Selection.TypeText(dr["sinifi"].ToString());
                                    }

                                    if (fieldName == "ono")
                                    {
                                        myMergeField.Select();
                                        
                            oWord.Selection.TypeText(dr["ono"].ToString());
                                    }

                                    if (fieldName == "adi")
                                    {
                                        myMergeField.Select();
                                        
                            oWord.Selection.TypeText(dr["adi"].ToString());
                                    }

                                    if (fieldName == "soyadi")
                                    {
                                        myMergeField.Select();
                                        
                            oWord.Selection.TypeText(dr["soyadi"].ToString());
                                    }

                                    if (fieldName == "gtarihi")
                                    {
                                        myMergeField.Select();
                                        oWord.Selection.TypeText(DateTime.Parse(dr["gtarihi"].ToString()).ToShortDateString());
                                    }

                                    if (fieldName == "dtarihi")
                                    {
                                        myMergeField.Select();
                                        oWord.Selection.TypeText(DateTime.Parse(dr["gezilistemiz25.dtarihi"].ToString()).ToShortDateString());
                                    }

                                    if (fieldName == "gyeri")
                                    {
                                        myMergeField.Select();
                                        oWord.Selection.TypeText(dr["gyeri"].ToString());
                                    }
                                }                               
                            }
                            
                            oWordDoc.Activate();
                            oWord.Activate();
                         }

                        //conn.Close();
                        //cmd.Dispose();
                        //conn.Dispose();
                        oWord.ActiveDocument.SaveAs2(Path.Combine
(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Veli İzin Belgesi.docx"));
                        oWordDoc.Close(ref oFalse, ref oMissing, ref oMissing);
                        oWord.Quit();
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(oWordDoc);
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(oWord);
                        oWordDoc = null;
                        oWord = null;
                        //GC.WaitForPendingFinalizers();
                        //GC.Collect();
                        Cursor.Current = Cursors.Default;
                        MessageBox.Show("Veli İzin Belgesi 
                        Word formatında masaüstüne kaydedildi!");
                    }
                }
            }
        }
    }
    catch (Exception hata)
    {
        MessageBox.Show("İşlem Sırasında Hata Oluştu." + hata.Message);
    }
    }
Posted
Updated 6-Oct-23 9:33am
v3
Comments
Richard MacCutchan 6-Oct-23 9:51am    
It looks like you only save the last document that you have created. As far as I can see you create a new document for each database record, but you only save the final active one.

1 solution

Most likely, it's that It's because you are trying to type the new text in, and it's likely that the data goes to a buffer which is overwritten each time round the loop - and the documents themselves aren't "filled in" by the system until your method exits.

The way to check is to use the debugger to look at what the fields contain at the end of the loop body - it's probably empty - and to look at which student dataset is being inserted in all documents. If it's the last one, then "overwritten buffer" is probably the reason why.

How to fix it? Don;t know - I suspect you might need to look at doing the whole job in a very different way, but I don't play with word automation much at all, so I can't say "do this and that'll fix it".
 
Share this answer
 
Comments
Member 12505620 7-Oct-23 4:26am    
I know the reason but I couldn't solve the problem. How can we do it?
OriginalGriff 7-Oct-23 5:00am    
Read my last paragraph?

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