数据未通过SQLDataAdapter加载到GridView

问题描述 投票:0回答:3

我是ASP.NET的新手,使用下面的查询来获取SQLDataAdapter中的数据以进行GridView显示。但看起来数据不是在SQLDataAdapter本身中获取的。相同的代码在SQLReader中运行良好。谁能帮助我理解我在这里做错了什么?

SqlConnection conn = new SqlConnection(connectionString);
        if (conn.State == ConnectionState.Closed)
        {
            conn.Open();
        }

        String sql = "Select top 100 * from xyz";
        SqlCommand cmd = new SqlCommand(sql, conn);

        SqlDataAdapter adapter = new SqlDataAdapter(cmd);

        DataSet Output = new DataSet();
        adapter.Fill(Output, "out");
        GridViewOutput.DataSource = Output.Tables["out"];

        /*  using (SqlCommand cmd = new SqlCommand(sql, conn))
          {
              using (SqlDataReader reader = cmd.ExecuteReader())
              {
                  while (reader.Read())
                  {
                      Response.Write( reader.GetString(0)+ reader.GetString(2));
                  }
              }

          }*/

      conn.Close();
c# asp.net sql-server
3个回答
0
投票

你需要打电话 -

GridViewOutput.DataBind()

指定数据源后。

更多关于此 -

https://docs.microsoft.com/en-us/dotnet/api/System.Web.UI.WebControls.GridView.DataBind?view=netframework-4.7.2


0
投票

你错过了绑定Gridview的行。

    SqlConnection conn = new SqlConnection(connectionString);
    if (conn.State == ConnectionState.Closed)
    {
        conn.Open();
    }

    String sql = "Select top 100 * from xyz";
    SqlCommand cmd = new SqlCommand(sql, conn);

    SqlDataAdapter adapter = new SqlDataAdapter(cmd);

    DataSet Output = new DataSet();
    adapter.Fill(Output, "out");
    GridViewOutput.DataSource = Output.Tables["out"];
    GridViewOutputData.DataBind();

    /*  using (SqlCommand cmd = new SqlCommand(sql, conn))
      {
          using (SqlDataReader reader = cmd.ExecuteReader())
          {
              while (reader.Read())
              {
                  Response.Write( reader.GetString(0)+ reader.GetString(2));
              }
          }

      }*/

  conn.Close();

0
投票

设置数据源后,您忘记包含DataBind()方法。 GridView数据绑定的正确方法应该是这样的:

SqlDataAdapter adapter = new SqlDataAdapter(cmd);

DataSet output = new DataSet();
adapter.Fill(Output, "out");
GridViewOutput.DataSource = Output; // bind directly to DataSet
GridViewOutput.DataBind(); // bind to grid
© www.soinside.com 2019 - 2024. All rights reserved.