我现在有一个DataTable,代码如下:
DataTable dt =  dcFunction.GetDataTable(funcId);
当我在遍历dt时:
for(int i=0;i<dt.Rows.Count;i++)
{
  string str1 = dt.Rows[i]["authorName"];
  string str2 = dt.Rows[i]["funcName"];
}
但是如果这个返回的dt为空的时候,也就是没有查询到数据时,总是报错,说dt中没有数据,可是我想要得到的是如果dt中没有数据的话,把str1和str2的赋为"",而不是报错,我想屏蔽掉这个错误!!也就是说查到数据时str1和str2中就是查到的数据,如果查不到,str1和str2 等于""

解决方案 »

  1.   

    是不是GetDataTable里面有问题?另外string str1 = String.Empty;
    string str2 = String.Empty;
    然后
    for(int i=0;i<dt.Rows.Count;i++)
    {
        str1 = dt.Rows[i]["authorName"];
        str2 = dt.Rows[i]["funcName"];
    }
      

  2.   

    for(int i=0;i<dt.Rows.Count;i++)
    {
      string str1 = dt.Rows[i]["authorName"];
      string str2 = dt.Rows[i]["funcName"];
    }变量重定义了。另外,没有数据应该不会报错,比如如果没数据,下面这个就应该为空字符串。dt.Rows[i]["authorName"].ToString();
      

  3.   

    string str1 = "";
    string str2 = "";for(int i=0;i<dt.Rows.Count;i++)
    {
        str1 = dt.Rows[i]["authorName"].ToString();
        str2 = dt.Rows[i]["funcName"].ToString();
    }
      

  4.   

    如果没有数据也不会报错的.你在for里面string str1,str2,这样你想咋搞?是不是dcFunction.GetDataTable(funcId);返回的是null值?
      

  5.   

    string str1 = (dt.Rows[i]["authorName"] == null) ? String.Empty : (string)dt.Rows[i]["authorName"];
      string str2 = (dt.Rows[i]["funcName"] == null) ? String.Empty : (string)dt.Rows[i]["funcName"];
      

  6.   

    如果是null的话.dt.Rows.Count这里就会报错了.
      

  7.   

    加个断点看一看..监视下返回的dt.Rows.Count
      

  8.   

    加null判断处理
    Or
     str1 = dt.Rows[i]["authorName"].ToString()+"";