数据集没有填满

时间:2012-08-13 11:12:23

标签: c# asp.net ado.net

我在ASP.NET页面中有一个简单的搜索页面,我在其中填写基于SQL Query的数据集。

            con.Open();    
            cmd.ExecuteNonQuery();
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;
            DataSet ds = new DataSet();
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    da.Fill(ds, "Emp");
                    GridView1.DataSource = ds;
                    GridView1.DataBind();
                }

            }
            else
            {
                Label2.Text = "Data not found";

            }
            con.Close();

但即使搜索项存在,我也将此结果视为“未找到数据”..为什么不执行if语句?

4 个答案:

答案 0 :(得分:1)

正如其他人建议您需要移动一行代码:

        con.Open();    
        cmd.ExecuteNonQuery();
        SqlDataAdapter da = new SqlDataAdapter();
        da.SelectCommand = cmd;
        DataSet ds = new DataSet();
        da.Fill(ds, "Emp");   // SEE THIS LINE!
        if (ds.Tables.Count > 0)
        {
            if (ds.Tables[0].Rows.Count > 0)
            {

                GridView1.DataSource = ds;
                GridView1.DataBind();
                Label2.Text = string.Empty;
            }

        }
        else
        {
            GridView1.DataSource = null;
            GridView1.DataBind();
            Label2.Text = "Data not found";

        }
        con.Close();

答案 1 :(得分:0)

你错过了

dataadapter.fill(ds)

答案 2 :(得分:0)

由于您在尝试填充数据集之前已经执行了查询,因此可能无法正常工作。尝试删除cmd.ExecuteNonQuery();.此外,非查询命令不会返回任何结果。确保您的查询确实返回结果。

答案 3 :(得分:0)

嗨,请尝试将其工作为我的gridview

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConectionString"].ConnectionString);

            SqlCommand cmd = new SqlCommand("Select * from Tbl_Employee", con);

            SqlDataAdapter da = new SqlDataAdapter(cmd);

            DataSet ds = new DataSet();
            da.Fill(ds);
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    gv1.DataSource = ds.Tables[0];
                    gv1.DataBind();
                }
            }
相关问题