Datagridview foreach nested loop

Sushil Agarwal 381 Reputation points
2021-08-06T03:39:31.82+00:00

Dear Experts,
from a datagridview having columns ac_code, filepath, email id i want to zip files of each same ac_code and email them.

how within foreach loop i can loop for same ac_code get the zip created and emailed once only

i tried with following code, zip file gets created and the loop is completed without entering the email sending code, if there are only records of single ac_code

            dgv1.Sort(dgv1.Columns["ac_code"], ListSortDirection.Ascending);  
            string ac_code = "", zippath = "";  
            foreach (DataGridViewRow dgvbills in dgv1.Rows)  
            {  
                if (string.IsNullOrWhiteSpace(ac_code)  
                    || ac_code.Equals(dgvbills.Cells["ac_code"].Value.ToString()))  
                {  
                    ac_code = dgvbills.Cells["ac_code"].Value.ToString();  
                    zippath = Path.GetTempPath() + @"\" + ac_code + ".Zip";  
                    string SignedEinv = @"C:\eInvoices\Response\" +  
                            dgvbills.Cells["doc_no"].Value.ToString() + "x" +  
                            dgvbills.Cells["doc_gl"].Value.ToString() + "x" +  
                            dgvbills.Cells["finyear"].Value.ToString() + ".json";  
                    if (!File.Exists(SignedEinv))  
                        continue;  
                    //create zip file  
                    using (FileStream zipToOpen = new FileStream(zippath, FileMode.OpenOrCreate))  
                    {  
                        using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))  
                        {  
                            archive.CreateEntryFromFile(SignedEinv, Path.GetFileName(SignedEinv), CompressionLevel.Optimal);  
                        }  
                    }  
                    continue;  
                }  
                lblNoofRecord.Text= zippath;  
                string emailid = "";  
                using (SqlConnection con = new SqlConnection(Appvaribales.ConnectionString))  
                {  
                    SqlCommand cmd = new SqlCommand("select dbo.fnEinvEmailId(@mainsl_ui,@department)", con);  
                    cmd.CommandType = CommandType.Text;  
                    cmd.Parameters.Add(new SqlParameter("@mainsl_ui", dgvbills.Cells["mainsl_ui"].Value.ToString()));  
                    cmd.Parameters.Add(new SqlParameter("@department", "EINVOICE"));  
                    try  
                    {  
                        con.Open();  
                        emailid = (string)cmd.ExecuteScalar();  
                        con.Close();  
                    }  
                    catch (Exception ex)  
                    {  
                        MessageBox.Show(ex.ToString());  
                    }  
                }  
                if (string.IsNullOrWhiteSpace(emailid))  
                {  
                    MessageBox.Show("No Email Id in EINVOICE deaprtment Of A/c:" +  
                        dgvbills.Cells["ac_code"].Value.ToString() + " is Found");  
                    continue;  
                }  
                //  
  
                ac_code = dgvbills.Cells["ac_code"].Value.ToString();  
  
                Outlook.Application oApp = new Outlook.Application();  
                // Get the NameSpace and Logon information.  
                Outlook.NameSpace oNS = oApp.GetNamespace("mapi");  
  
                // Log on by using a dialog box to choose the profile.  
                oNS.Logon(Missing.Value, Missing.Value, true, true);  
  
                // Alternate logon method that uses a specific profile.  
                // TODO: If you use this logon method,  
                //  change the profile name to an appropriate value.  
                //oNS.Logon("YourValidProfile", Missing.Value, false, true);  
  
                // Create a new mail item.  
                Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);  
  
                // Set the subject.  
                oMsg.Subject = "E-inoices Json Copies";  
  
                // Set HTMLBody.  
                //string currdispatches = "";  
                oMsg.HTMLBody = " Dispatched on:" + dgvbills.Cells["gateoutdate"].Value.ToString() +  
                            Environment.NewLine;  
                Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;  
                // TODO: Change the recipient in the next line if necessary.  
                string[] receipants = emailid.Split(';');  
                for (int i = 0; i < receipants.Length; i++)  
                {  
                    if (string.IsNullOrWhiteSpace(receipants[i]))  
                        continue;  
                    Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add(receipants[i]);  
                    oRecip.Resolve();  
                }  
  
                //now attached the file  
  
                if (!string.IsNullOrWhiteSpace(zippath))  
                {  
                    //Add an attachment.  
                    string sDisplayName = "ScheduleVsDispatch";  
                    int iPosition = (int)oMsg.Body.Length + 1;  
                    int iAttachType = (int)Outlook.OlAttachmentType.olByValue;  
                    Outlook.Attachment oAttach = oMsg.Attachments.Add(zippath, iAttachType, iPosition, sDisplayName);  
                }  
                oMsg.Send();  
  
                // Log off.  
                oNS.Logoff();  
  
                // Clean up.  
                //oRecip = null;  
                oRecips = null;  
                oMsg = null;  
                oNS = null;  
                oApp = null;  
                //  
                if (pgbBillItemQuery.Value == pgbBillItemQuery.Maximum)  
                {  
                    pgbBillItemQuery.Value = pgbBillItemQuery.Minimum;  
                }  
                else  
                {  
                    //pgbEmail.Value += 1;  
                    pgbBillItemQuery.PerformStep();  
                }  
            }  


  
Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,857 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,382 questions
{count} votes

Accepted answer
  1. Sushil Agarwal 381 Reputation points
    2021-08-12T12:17:35.707+00:00

    This ishow i resolved my problem
    for (int i = 0; i < dgv1.Rows.Count - 1; i++)
    {
    DataGridViewRow dgvbills = dgv1.Rows[i];
    string ac_code = dgvbills.Cells["ac_code"].Value.ToString();
    string zippath = Path.GetTempPath() + ac_code + ".Zip";
    finescompressed = 0;
    //emailsent = false;
    while (ac_code.Equals(dgvbills.Cells["ac_code"].Value.ToString()))
    {
    string gateoutdate = dgvbills.Cells["gateoutdate"].Value.ToString();
    string SignedEinv = @"C:\eInvoices\Response\" +
    dgvbills.Cells["doc_no"].Value.ToString() + "x" +
    dgvbills.Cells["doc_gl"].Value.ToString() + "x" +
    dgvbills.Cells["finyear"].Value.ToString() + ".json";

                        if (string.IsNullOrEmpty(gateoutdate))  
                        {  
                            sw.WriteLine(SignedEinv + ":Pending For Gateout");  
                        }  
                        else  
                        {  
                            if (File.Exists(SignedEinv))  
                            {  
                                //https://learn.microsoft.com/en-us/dotnet/standard/io/how-to-compress-and-extract-files  
                                //create zip file  
                                using (FileStream zipToOpen = new FileStream(zippath, FileMode.OpenOrCreate))  
                                {  
                                    using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))  
                                    {  
                                        archive.CreateEntryFromFile(SignedEinv, Path.GetFileName(SignedEinv), CompressionLevel.Optimal);  
                                        finescompressed++;  
                                    }  
                                }  
                            }  
                            else  
                            {  
                                sw.WriteLine(SignedEinv+":Not Found");  
                            }  
                        }  
                        if (i < dgv1.Rows.Count - 1)  
                        {  
                            i++;  
                            dgvbills = dgv1.Rows[i];  
                        }  
                        else  
                        {  
                            break;  
                        }  
                    }  
                    if (finescompressed <= 0)  
                    {  
                        sw.WriteLine("No Files In Zip To Email");  
                        continue;  
                    }  
                    lblNoofRecord.Text = zippath;  
                    //get email id from contact table   
                    string emailid = "";  
                    using (SqlConnection con = new SqlConnection(Appvaribales.ConnectionString))  
                    {  
                        //SQL Function Example  
                        /*  
                         * Get email id from mainsl contacts for department = 'EINVOICE'  
                         */  
                        SqlCommand cmd = new SqlCommand("select dbo.fnEinvEmailId(@mainsl_ui,@department)", con);  
                        cmd.CommandType = CommandType.Text;  
                        cmd.Parameters.Add(new SqlParameter("@mainsl_ui", dgvbills.Cells["mainsl_ui"].Value.ToString()));  
                        cmd.Parameters.Add(new SqlParameter("@department", "EINVOICE"));  
                        try  
                        {  
                            con.Open();  
                            emailid = (string)cmd.ExecuteScalar();  
                            con.Close();  
                        }  
                        catch (Exception ex)  
                        {  
                            MessageBox.Show(ex.ToString());  
                        }  
                    }  
                    if (string.IsNullOrWhiteSpace(emailid))  
                    {  
                        sw.WriteLine("No Email Id in EINVOICE deaprtment Of A/c:" +  
                            dgvbills.Cells["ac_code"].Value.ToString() + " is Found");  
                        continue;  
                    }  
                    sendOutlookemail(zippath, emailid,ref sw);  
                    if (pgbBillItemQuery.Value == pgbBillItemQuery.Maximum)  
                    {  
                        pgbBillItemQuery.Value = pgbBillItemQuery.Minimum;  
                    }  
                    else  
                    {  
                        //pgbEmail.Value += 1;  
                        pgbBillItemQuery.PerformStep();  
                    }  
                }  
    
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Bonnie DeWitt 811 Reputation points
    2021-08-09T04:48:29.02+00:00

    I think the problem is the continue; after you create the zip file.


    ~~Bonnie DeWitt [MVP since 2003]
    [http://geek-goddess-bonnie.blogspot.com]1

    0 comments No comments