DataGridVIew行到电子邮件

时间:2017-04-01 17:50:38

标签: c# datagridview

我有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);
            }
        }
    }

这是代码,但我现在收到4封邮件,因为SendMail()在foreach循环中,如果我把它取出,则无法访问本地变量连接..?如何解决这个问题?我使用email.Skip(1).Take(4)来省略一些不必要的值?提前致谢

1 个答案:

答案 0 :(得分:0)

将声明List<string> email = new List<string>();移到foreach之外。不确定为什么需要Skip(1).Take(4)

我建议使用以下代码:

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