4

我目前正在尝试为我的 gridview 进行分页,但是一旦我允许在我的 gridview 中进行分页,它就会给我这个错误:数据源不支持服务器端数据分页。

这是我的 gridview 代码:

        SqlDataReader reader = cmd.ExecuteReader();
        GridView1.DataSource = reader;
        GridView1.DataSourceID = null;
        GridView1.Visible = true;
        GridView1.AllowPaging= true;
        GridView1.DataBind(); 
        conn.Close();
4

3 回答 3

7

SqlDataReader是只进的。服务器端分页需要能够前后遍历数据源。使用不同的数据源,比如SqlDataAdapter,它支持双向遍历。

示例(根据要求):

string query = string.Empty;
SqlConnection conn = null;
SqlCommand cmd = null;
SqlDataAdapter da = null;
DataSet ds = null;

try {
    query = "SELECT * FROM table WHERE field = @value";
    conn = new SqlConnection("your connection string");

    cmd = new SqlCommand(query, conn);
    cmd.Parameters.Add("value", SqlDbType.VarChar, 50).Value = "some value";

    da = new SqlDataAdapter(cmd);
    ds = new DataSet();
    da.Fill(ds);

    if (ds.Tables.Count > 0) {
        GridView1.DataSource = ds.Tables(0);
        GridView1.AllowPaging = true;
        GridView1.DataBind();
    }
} catch (SqlException ex) {
//handle exception
} catch (Exception ex) {
//handle exception
} finally {
    if (da != null) {
        da.Dispose();
    }
    if (cmd != null) {
        cmd.Dispose();
    }
    if (conn != null) {
        conn.Dispose();
    }
}

SqlDataAdapter也来自System.Data.SqlClient命名空间。

于 2013-07-12T03:43:48.667 回答
1

您是否尝试过使用 SqlDataAdapter 用您的 SQL 结果填充 DataSet/DataTable?然后将该 DataTable 用作 GridView 的数据源。填充 DataTable 的基本框架:

public DataTable GetDataTable(String connectionString, String query)
{
    DataTable dataTable = new DataTable();

    try
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();

            using (SqlCommand command = new SqlCommand(query, connection))
            {
                using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command))
                {
                    dataAdapter.Fill(dataTable);
                }
            }
        }
    }
    catch
    {   

    }

    return dataTable;
}

然后您可以将该 DataTable 用作您的 GridView 数据源:

String connectionString = "Data Source=<datasource>;Initial Catalog=<catalog>;User Id=<userID>;Password=<password>;";
String query = "SELECT * FROM TABLE_NAME WHERE ID=BLAH";

GridView1.DataSource = GetDataTable(connectionString, query);
GridView1.DataSourceID = null;
GridView1.Visible = true;
GridView1.AllowPaging= true;
GridView1.DataBind();

希望这会有所帮助。

于 2013-07-12T03:30:11.497 回答
0

您可以通过两种方式将分页应用于网格视图

(1) 在您的 gridview 中使用对象数据源

(2)使用jquery数据表

于 2013-07-12T03:45:57.547 回答