For Each循环NullReferenceException

Pan*_*aNL 1 c# foreach datagridview

我使用foreach循环使用以下代码从我的datagridview中获取数据.

foreach (DataGridViewRow row in this.dataGridMultiSubmit.Rows)
{
    Model = row.Cells[0].Value.ToString();
    Module = row.Cells[1].Value.ToString();
    Section = row.Cells[2].Value.ToString();
    FunctionValue = row.Cells[3].Value.ToString();
    NewValue = row.Cells[4].Value.ToString();
    DefaultValue = row.Cells[5].Value.ToString();
    Description = row.Cells[6].Value.ToString();

    MessageBox.Show(Model + Module + Section + FunctionValue + NewValue + DefaultValue + Description);
}
Run Code Online (Sandbox Code Playgroud)

它在消息框中正确返回所有行,但当它通过所有行运行时它给我NullReferenceException未处理,我该如何解决这个问题?

Gra*_*ICA 10

如果你在迭代所有行Value的过程中有任何一个null,那么调用ToString()将抛出异常.

尝试改为:

Model = Convert.ToString(row.Cells[0].Value);
Run Code Online (Sandbox Code Playgroud)

该方法进行Convert.ToString()了额外的检查.

  • 如果值为null,则返回空字符串.
  • 如果不是null,那么它执行一个ToString().

根据您的注释,您还需要确保不迭代显示在网格底部的新行.有一个叫做的内置属性IsNewRow.

获取一个值,该值指示该行是否是新记录的行.

foreach (DataGridViewRow row in this.dataGridMultiSubmit.Rows)
{
    if (row.IsNewRow)
        continue;       // skip row, continue on to the next iteration

    ...
}
Run Code Online (Sandbox Code Playgroud)