NullReferenceException有什么解决方案?

时间:2016-07-17 19:08:42

标签: c# database postgresql-9.1

我使用以下代码读取存储在img表格tb21列中的所有图片路径。

NpgsqlDataAdapter da = new NpgsqlDataAdapter("SELECT img FROM tb21", dbcon);
DataSet ds = new DataSet();
List<string> img1 = new List<string>();

foreach (DataRow row in ds.Tables["tb21"].Rows)
{ 
    img1.Add(row["img"].ToString()); 
}

但是,我收到了一个错误:

  

对象引用未设置为对象的实例

这是什么解决方案?

1 个答案:

答案 0 :(得分:1)

if (ds.Tables.Count > 0)
  foreach (DataRow row in ds.Tables["tb21"].Rows)
    if(row["img"] != null && row["img"] != DBNull.Value)
       { img1.Add(row["img"].ToString()); }