以相反的顺序循环访问DataGridView

时间:2014-02-19 23:32:35

标签: c# visual-studio-2012

我正在使用这个完美无缺的代码并从gridview的开始循环到结束,我需要它以另一种方式执行(从最后一行开始并回到第一行)

欢呼声

for (int i2 = 0; i2 < dataGridView1.Rows.Count - 1; i2++)
{
    DataGridViewRow rows = dataGridView1.Rows[i2];

    MetaWeblogClient blogClient = new MetaWeblogClient();
    blogClient.NewPost((rows.Cells["imageurl"].Value).ToString(),
                       (rows.Cells["title"].Value).ToString(), 
                       (rows.Cells["videourl"].Value).ToString());
    (rows.Cells["done"].Value) = "yes";
    blogClient.Dispose();
}

2 个答案:

答案 0 :(得分:1)

倒退工作应该很容易。你尝试过这样的事吗?

更新:因为不清楚你在哪里得到空引用异常,也许你应该在空检查中将你的调用包装到行的Cells属性中:

for (int i2 = dataGridView1.Rows.Count - 1; i2 >= 0; i2--) { 

  DataGridViewRow row = dataGridView1.Rows[i2];

  // Check for null value in row
  if (row != null && row.Cells["done"] != null) {
      row.Cells["done"].Value = "yes"
  } 
}

答案 1 :(得分:1)

我认为如果你稍微清理一下代码,你可能会发现问题更容易了。

您的命名也很难遵循,因此我会尽力对此进行评论以突出显示更改:

for (int i2 = dataGridView1.Rows.Count - 1; i2 >= 0; i2--)
{
    //Don't name a singular item with a plural name -- rows should be row
    DataGridViewRow row = dataGridView1.Rows[i2];

    //MetaWeblogClient implements IDisposable so we can wrap it in a using statement
    using (MetaWeblogClient blogClient = new MetaWeblogClient())
    {
        //You do not need the parenthesis around the values
        blogClient.NewPost(row.Cells["imageurl"].Value.ToString(),
                           row.Cells["title"].Value.ToString(), 
                           row.Cells["videourl"].Value.ToString());
        row.Cells["done"].Value = "yes";
    }
    //blogClient is automatically disposed of here because of the using statement
}

如果此时收到NullReferenceException,可能是因为当您遍历网格时,其中一行中没有数据,或者您的某个列名称不正确。您可以通过逐步调试调试器中的代码并观察每个值的变化来轻松识别此类错误。

相关问题