由於GridView的資料來源是後臺CS檔案中程式碼繫結的。所以程式執行時,點選分頁數後沒有反應。解決辦法如下:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlDataSource source = new SqlDataSource();
protected void Page_Load(object sender, EventArgs e)
{
}
private void DBind()
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["TransportConnectionString"].ConnectionString;
source.ConnectionString = ConfigurationManager.ConnectionStrings["TransportConnectionString"].ConnectionString;
string sql = "SELECT * from Customer where id<>'' ";
if (this.客戶名稱.Text != "")
{
sql = sql + " and 客戶編碼 LIKE '%" + this.客戶名稱.Text + "%' ";
}
source.SelectCommand = sql;
GridView1.DataSourceID = "";
GridView1.DataSource = "";
GridView1.DataSource = source;
GridView1.DataBind();
}
protected void SearchButton_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["TransportConnectionString"].ConnectionString;
source.ConnectionString = ConfigurationManager.ConnectionStrings["TransportConnectionString"].ConnectionString;
string sql = "SELECT * from Customer where id<>'' ";
if (this.客戶名稱.Text != "")
{
sql = sql + " and 客戶編碼 LIKE '%" + this.客戶名稱.Text + "%' ";
}
source.SelectCommand = sql;
GridView1.DataSourceID = "";
GridView1.DataSource = "";
GridView1.DataSource = source;
GridView1.DataBind();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex=e.NewPageIndex;
DBind();
}
}
需要注意的是,我增加了一個方法,和繫結事件按鈕是一樣的。需要在PageIndexChanging事件中重新繫結資料來源才可以。但是這個辦法有一個問題。就是每次切換頁數的時候,都會從資料庫中查詢全部的資料,所以效率上會有問題。看大家有什麼解決辦法沒有?