question

SushilAgarwal-8271 avatar image
0 Votes"
SushilAgarwal-8271 asked SushilAgarwal-8271 answered

Datagridview foreach nested loop

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();
                 }
             }


dotnet-csharpwindows-forms
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi @SushilAgarwal-8271,
>>zip file gets created and the loop is completed without entering the email sending code
Based on your code, what specific problem did you encounter?
Best Regards,
Daniel Zhang

0 Votes 0 ·
SushilAgarwal-8271 avatar image
0 Votes"
SushilAgarwal-8271 answered

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://docs.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();
                 }
             }
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

BonnieDeWitt-QnA avatar image
0 Votes"
BonnieDeWitt-QnA answered BonnieDeWitt-QnA edited

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


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


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.