2016-09-15 189 views
0

我有以下代碼C#「繼續」不按預期運行

private void bgwSendMail_DoWork(object sender, DoWorkEventArgs e) 
    { 
     DataSet ds = getMailToSend(); 
     DataTable table = ds.Tables[0]; 
     { 
      foreach (DataRow row in table.Rows) 
      { 
       { 
        string attachment1 = ds.Tables[0].Rows[0]["Attachment1"].ToString(); 
        string attachment2 = ds.Tables[0].Rows[0]["Attachment2"].ToString(); 
        string attachment3 = ds.Tables[0].Rows[0]["Attachment3"].ToString(); 
        string attachment4 = ds.Tables[0].Rows[0]["Attachment4"].ToString(); 
        string mailTo = ds.Tables[0].Rows[0]["EmailTo"].ToString(); 
        string mailSubject = ds.Tables[0].Rows[0]["EmailSubject"].ToString(); 
        string mailBody= ds.Tables[0].Rows[0]["EmailBody"].ToString(); 
        string uid = ds.Tables[0].Rows[0]["uid"].ToString(); 

        if (String.IsNullOrEmpty(attachment1)) 
        { 
         //TODO Send Email Straight away ignore rest 

        } 
        else 
        { 
         if (!String.IsNullOrEmpty(attachment1)) 
         { 
          bool attachment1Exists = checkFileExists(attachment1); 
          if (attachment1Exists == false) 
          { 

           continue; 
          } 
         } 

現在我所期望的,當我們打到繼續(它被擊中)在底部,我們應該退回到如下面的foreach,並移動到下一條記錄在數據集中

enter image description here

這不會發生,它遍歷相同的記錄,從該繼續來自一遍又一遍,這正常嗎?

如果是正常的,一旦它退出一次,最好的方法是讓foreach忽略數據表中的那一行?

+12

你實際上並沒有在使用'row'。您正在不斷使用'ds.Tables [0] .Rows [0]'。有意義的是,它總是處理相同的數據。 –

回答

6

continue按預期工作。

您正在枚舉表中的所有行,但您沒有使用它。相反,您總是訪問表中的第一行:

DataTable table = ds.Tables[0]; 
foreach(DataRow row in table.Rows) 
{ 
    string attachment1 = ds.Tables[0].Rows[0]["Attachment1"].ToString(); 
    // ... 
} 

您總是訪問ds.Tables[0].Rows[0]

相反,你應該使用此代碼:

foreach(DataRow row in table.Rows) 
{ 
    string attachment1 = row["Attachment1"].ToString(); 
    // ... 
} 

所以你實際上是枚舉表中的所有行如預期,這不是一個無限循環,但你不使用表格中的每一行,但只有第一。

+0

什麼木板,我一直在撓我的頭一個小時,謝謝! –

4

變化

string attachment1 = ds.Tables[0].Rows[0]["Attachment1"].ToString();

string attachment1 = row["Attachment1"].ToString();

和DataRow中所有其他後續引用。