C#“继续”不按预期运行
问题描述:
我有以下代码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,并移动到下一条记录在数据集中
这不会发生,它遍历相同的记录,从该继续来自一遍又一遍,这正常吗?
如果是正常的,一旦它退出一次,最好的方法是让foreach
忽略数据表中的那一行?
答
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
什么木板,我一直在挠我的头一个小时,谢谢! –
答
变化
string attachment1 = ds.Tables[0].Rows[0]["Attachment1"].ToString();
到
string attachment1 = row["Attachment1"].ToString();
和DataRow中所有其他后续引用。
你实际上并没有在使用'row'。您正在不断使用'ds.Tables [0] .Rows [0]'。有意义的是,它总是处理相同的数据。 –