2013-07-12 44 views
4

我目前正在嘗試爲我的gridview進行分頁,但是一旦我允許在我的gridview中分頁,它會給我這個錯誤:數據源不支持服務器端數據分頁。數據源不支持服務器端數據分頁

這是我的GridView代碼:

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

'SqlDataReader'是隻進。尋呼需要向前和向後。使用不同的數據源:http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.aspx – pete

+0

我可以舉個例子嗎? –

回答

1

您是否嘗試過使用SqlDataAdapter來填充DataSet/DataTable中與您的SQL結果?然後使用該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; 
} 

然後你就可以使用數據表作爲你的GridView的DataSource:

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(); 

希望這將有助於。

+0

當我嘗試這種方式,並在'GridView1.DataSource = GetDataTable(connectionString,query);'我得到了這兩個錯誤:連接字符串不存在於當前上下文中,查詢在當前上下文中不存在。 –

+0

您必須在調用GetDataTable()之前定義連接字符串和查詢變量:p它們只是佔位符。 – digiliooo

+0

現在顯示connectionString和查詢變量的值 – digiliooo

6

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命名空間。

+1

很棒:)爲我工作 –

+0

我無法告訴你我浪費了多少時間。感謝您結束這次挫折。 –

0

您可以通過兩種方式申請

分頁到GridView

(1)使用對象數據源與你的GridView

(2)使用jQuery的DataTable

相關問題