简体   繁体   English

DataGridVIew行发送电子邮件

[英]DataGridVIew row to e-mail

I have DataGridView control where I want cell values from every selected row to be send as an e-mail body text as one string line: 我有DataGridView控件,我希望将每个选定行中的单元格值作为一个字符串行作为电子邮件正文发送:

        private void buttonReport_Click(object sender, EventArgs e)
    {
        MailAddress from = new MailAddress("hi@greetings.com", "Hello");
        MailAddress to = new MailAddress("hi1234@gmail.com", "Hi");
        string join;

        foreach (DataGridViewRow row in dgvTest.Rows)
        {
            List<string> email = new List<string>();
            {
                if (Convert.ToBoolean(row.Cells[cbSelect.Name].Value) == true)
                {
                    foreach (DataGridViewCell cell in row.Cells)
                    {
                        if (cell.Value != null)
                        {
                            email.Add(cell.Value.ToString());
                        }
                    }
                }
            }
            foreach (string items in email.Skip(1).Take(4))
            {
                join = String.Join(", ", items.ToString());
                SendEmail("Hi!", from, to, join);
            }
        }
    }

This is the code, however I am getting 4 mails now because the SendMail() is in the foreach loop, if I take it out, the local variable join is not accessible..? 这是代码,但是我现在收到4封邮件,因为SendMail()在foreach循环中,如果我将其取出,则无法访问本地变量join。 how to work around this? 如何解决这个问题? I am using the email.Skip(1).Take(4) to omit some unnecessary values? 我正在使用email.Skip(1).Take(4)省略一些不必要的值? Thanks in advance 提前致谢

Move declaration List<string> email = new List<string>(); 移动声明List<string> email = new List<string>(); outside foreach. 外面foreach。 Not sure why you need Skip(1).Take(4) 不确定为什么需要Skip(1).Take(4)

I suggest following code: 我建议以下代码:

//declared somewhere above
List<string> CellsForReport = new List<string>{ "item1", "item2", "item3", "item4" }

//code inside buttonReport_Click
List<string> emails = new List<string>();
foreach (DataGridViewRow row in dgvTest.Rows)
{
  if (Convert.ToBoolean(row.Cells[cbSelect.Name].Value) == true)
  {
    //list to collect current row items
    var currentMailItems = new List<string>()
    foreach (var cellName in CellsForReport )
    {
       //this can throw exception if you specified wrong name above
       var cell = row.Cells[cellName];
       if (cell.Value != null)
       {
         currentMailItems.Add(cell.Value.ToString());
       }
    }
    //construct email text from row
    var finalEmailText = string.Join(", ", currentMailItems);
    emails.Add(finalEmailText);
  }
}
//sending 1 email per row
foreach (var email in emails)
{
  SendEmail("Hi!", from, to, email);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM