【问题标题】:SqlDataSource lost the where clause during pagingSqlDataSource 在分页期间丢失了 where 子句
【发布时间】:2017-06-14 10:18:05
【问题描述】:

我有一个带有此查询的SqlDataSource

SELECT [ProductName], [Debscription], [Price] FROM [MyDb] WHERE ([Date1] >= @Date1) ORDER BY [ProductName]">

当我加载页面时,它运行良好并且只显示我想要的产品。 当我尝试更改 GridView 的页面时,例如转到第 2 页,它会刷新页面并生成大量页面索引,因为 where 子句丢失。

我该如何解决这个问题?

我以为语句是自动保存的,但不是。

如何在分页时保存 where 子句?

【问题讨论】:

    标签: sql asp.net vb.net


    【解决方案1】:

    对于动态分页,您应该使用 ObjectDataSource 而不是 SqlDataSource。

    【讨论】:

      【解决方案2】:

      如果您希望网格处理分页,请将其绑定到 DataTable 或 DataSet。例如:

      private void Page_Load(object sender, System.EventArgs e)
      {
         if (!Page.IsPostBack)
             BindData();
      }
      
      private void BindData()
      {
          // Connect to the Database
          SqlConnection myConnection = new SqlConnection(connection string);
      
          // Retrieve the SQL query results and bind it to the DataGrid
          string SQL_QUERY = "SELECT ProductName, UnitPrice, UnitsInStock " +
                        "FROM Products";
          SqlCommand myCommand = new SqlCommand(SQL_QUERY, myConnection);
      
          // Use a DataTable – required for default paging
          SqlDataAdapter myAdapter = new SqlDataAdapter(myCommand);
      
          DataTable myTable = new DataTable();
          myAdapter.Fill(myTable);
      
          dgProducts.DataSource = myTable;
          dgProducts.DataBind();
          myConnection.Close();
      }
      

      https://msdn.microsoft.com/en-us/library/aa479006.aspx

      【讨论】:

      • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。 - From Review
      • 我不确定原始答案/链接是否准确回答了问题,所以我跳过了代码。用代码更新。
      猜你喜欢
      • 2012-03-01
      • 2016-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-29
      • 2017-05-07
      相关资源
      最近更新 更多