2014-03-05 47 views
0

好了,所以我有有一個按鈕將數據導出到電子郵件中的數據網格,它目前與下面的代碼,創建一個新的郵件,並將其插入在DataGrid中顯示的第一行正確但不插入任何其他行。 我假設我需要一個循環IE我的foreach語句(儘管是空的)需要一些東西在那裏,但我不能弄明白,一直困住了幾個小時)基本上我只想循環遍歷從所列2列顯示的所有行,然後讓他們到變量,然後用它來插入新郵件項目的檢體...遍歷數據網格行,並得到變量C#

Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application(); 
Microsoft.Office.Interop.Outlook.MailItem mailItem = (MailItem)app.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem); 

foreach (DataGridViewRow rows in dataGridView2.SelectedRows) 
{ 


} 

var column1 = dataGridView2.Rows[0].Cells["dataGridViewTextBoxColumn2"].Value; 
var column2 = dataGridView2.Rows[0].Cells["dataGridViewTextBoxColumn1"].Value; 

mailItem.Body = column1.ToString() + " - " + column2.ToString(); 
mailItem.Subject = this.subjectText.Text; 
mailItem.To = this.senderText.Text; 

//mailItem.Attachment.Add(logPath);//logPath is a string holding path to the log.txt file 
//mailItem.Importance = Microsoft.Office.Tools.Outlook.OlImportance.olImportanceHigh; 
mailItem.Display(false); 

回答

2

首先,如果你想顯示的每一行,你需要dataGridView2.Rows更換dataGridView2.SelectedRows,那麼,只需在每次迭代中獲得column1和column2的值:

object column1 = ""; 
object column2 = ""; 
foreach (DataGridViewRow row in dataGridView2.Rows) 
{ 
    if(!item.IsNewRow) 
    { 
     column1 = item.Cells["dataGridViewTextBoxColumn1"].Value; 
     column2 = item.Cells["dataGridViewTextBoxColumn2"].Value; 
     mailItem.Body += column2 != null ? column2.ToString() : "" + " - " + 
         column1 != null ? column1.ToString() : "" + "\n"; 
} 
+0

得到空引用異常錯誤,猜測這是事做我的DataGrid的參考? – JoshF91

+0

哪一行產生錯誤? –

+0

它在foreach語句 – JoshF91

0

您可以做它這樣:

 StringBuilder builder = new StringBuilder(); 

     foreach (DataGridViewRow rows in dataGridView2.SelectedRows) 
     { 
      builder.AppendLine(
       ((rows.Cells["dataGridViewTextBoxColumn2"].Value == null) ? "" : rows.Cells["dataGridViewTextBoxColumn2"].Value.ToString()) + 
       " - " + 
      ((rows.Cells["dataGridViewTextBoxColumn1"].Value == null) ? "" : rows.Cells["dataGridViewTextBoxColumn1"].Value.ToString())); 


     } 

     mailItem.Body = builder.ToString(); 

另外,如果可能的話,嘗試使用列索引。