Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

data source does not support server-side data paging

Tags:

asp.net

i am currently trying to do paging for my gridview but once i allow paging in my gridview it will give me this error : The data source does not support server-side data paging.

this is my code for gridview :

        SqlDataReader reader = cmd.ExecuteReader();
        GridView1.DataSource = reader;
        GridView1.DataSourceID = null;
        GridView1.Visible = true;
        GridView1.AllowPaging= true;
        GridView1.DataBind(); 
        conn.Close();
like image 748
Por Weiting Avatar asked Feb 15 '23 22:02

Por Weiting


1 Answers

SqlDataReader is forward-only. Server-side Paging needs to be able to traverse the datasource both backward and forward. Use a different datasource, like SqlDataAdapter, which supports bi-directional traversal.

Example (as requested):

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 is also from the System.Data.SqlClient Namespace.

like image 79
pete Avatar answered Mar 03 '23 10:03

pete