数据库已接连好,这个方法想查找表‘notice’的所有记录,但’notice‘表为空,一个记录也没有。     public DataSet getList()
        {
            string sqltxt = "select * from [notice] ";
            SqlConnection cone = new SqlConnection(DbConnect);//Dbconnect为连接字符串
            SqlDataAdapter da = new SqlDataAdapter(sqltxt, cone);            DataSet ds = new DataSet();
            try
            { 
                cone.Open();    
                da.Fill(ds);
            }
            catch
            {
                throw;
            }
            finally
            {
                cone.Close();
            }
            return ds;
        }
======================================================
问题是:当表为空时,这样读取会发生错误。我想无论表是否为空都能返回一个DataSet,诚心求教 !

解决方案 »

  1.   

    在使用 SqlDataAdapter 时无须手动打开或关闭连接
    public DataSet getList()
      {
      string sqltxt = "select * from [notice] ";
      SqlConnection cone = new SqlConnection(DbConnect);//Dbconnect为连接字符串
      SqlDataAdapter da = new SqlDataAdapter(sqltxt, cone);  DataSet ds = new DataSet();
      try
      {  
      da.Fill(ds);
      }
      catch
      {
      throw;
      }
      return ds;
      }
    使用
    DataSet ds = getList();
    if(ds.Tables.Count > 0)
    {
    ..........
    }
      

  2.   

    using(SqlConnection cone = new SqlConnection(DbConnect))
    {
    }
    if(ds.Tables[0].Rows.Count>0)
    {}
      

  3.   

    哦,是我说得不细,读取时是不会出什么错,是在使用时,比如:
    在Web层:
      public void DataBind()
        {
            BLL.notice bn = new BLL.notice();
            GridView1.DataSource = bn.getList();
            GridView1.DataBind();    }
    ===============================================
        当表为空时,这样会出现错误。我只想在DAL层动数据库,
     ‘初吻给了烟’ 大哥的方法
    =====================
    DataSet ds = getList();
    if(ds.Tables.Count > 0)
    {
    ..........
    }
    =====================
    判断后怎样返回一个DataSet?
      

  4.   

    public void DataBind()
      {
      BLL.notice bn = new BLL.notice();
    if(bn.getlist()>0)
    {
      GridView1.DataSource = bn.getList();
      GridView1.DataBind();
    }
    else
       Label1.text="当前没有数据";
      }
      

  5.   

    if(bn.getlist().tables[0].rows.count>0)
      

  6.   

    如果Dataset里面没有数据,给gridview绑定会出错吗?
    这个还没遇到过!等高手解答