利用Ajax實現DataGrid無重新整理分頁(AjaxGrid)

來源:互聯網
上載者:User

利用Ajax實現DataGrid無重新整理分頁(AjaxGrid)

DataGrid功能強大,我們只用寫幾行代碼就能夠實現複雜的頁面資料顯示。資料多的時候免不了要分頁顯示,DataGrdi本身內建分頁功能,但是當資料量少的時候很方便,當大資料量時,DataGrid得分頁機制就不太好了。於是在網上找到了一種比較好的利用預存程序實現分頁機制(用戶端想要第幾頁就取第幾頁資料,上十萬級的資料查詢也很快,資料量再多的時候就沒試過了,等有時間把利用預存程序分頁也寫在blog上)在工作中為了讓客戶用的更舒服點,也趕時髦,想利用Ajax來實現DataGrid無重新整理分頁。主要用RenderControl方法把DataGrid翻譯成Html代碼,然後用Web Service 返回。當然也可以用別的方法。

GenericAjaxWS.asmx.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Web;
using System.Web.Services;
using System.Configuration;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.IO;

namespace GenricAjaxWS
{
      [WebService(Namespace="http://localhost/GenricAjaxWS/")]
      public class GenricAjaxWS : System.Web.Services.WebService
      {
            SqlConnection con;
            SqlDataAdapter da;
            SqlCommand cmd;
            DataSet ds;

            public GenricAjaxWS()
            {
              InitializeComponent();
              con= new SqlConnection(ConfigurationSettings.AppSettings["Connect"]);
              da=new SqlDataAdapter("",con);
              cmd=new SqlCommand("",con);
              ds=new DataSet("TahaSchema");
            }

            #region Component Designer generated code

            //Required by the Web Services Designer
            private IContainer components = null;

            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {
            }

            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            protected override void Dispose( bool disposing )
            {
              if(disposing && components != null)
              {
                    components.Dispose();
              }
              base.Dispose(disposing);
            }
           
            #endregion
 
/// <summary>
/// this function accepts TSql statment and returns dataset
/// </summary>
 

            [WebMethod]
            public string getGrid(string sqlStr,int pageIndex)
            {
              da.SelectCommand.CommandText=sqlStr;
              da=new SqlDataAdapter(sqlStr,con);
              da.Fill(ds,"myTable");

              DataGrid dataGrid = new DataGrid();
              dataGrid.AutoGenerateColumns = true;
              dataGrid.DataSource = ds.Tables["myTable"].DefaultView;
              dataGrid.AllowPaging = true;
              dataGrid.PageSize = 4;
              dataGrid.PagerStyle.Visible = false;
              dataGrid.CurrentPageIndex = pageIndex;
              try
              {
                    dataGrid.DataBind();
              }
              catch(Exception)
              {

              }
              StringWriter wr = new StringWriter();
              HtmlTextWriter writer = new HtmlTextWriter(wr);
              dataGrid.RenderControl(writer);
              string gridHtml = wr.ToString();
              wr.Close();
              writer.Close();
              DropDownList ddl_Pager = new DropDownList();
              ddl_Pager.Attributes.Add("onchange","goToPage(this.value)");
              string pager="";
              for(int i=0;i<dataGrid.PageCount;i++)
              {
                ListItem lItem = new ListItem(i.ToString(),i.ToString());
                ddl_Pager.Items.Add(lItem);
                if(i==pageIndex)
                {
                  pager += "[background-color:#ffdd11;width" +
                         ":20px;align:center\"><a href=\"#\" onclick" +
                         "=\"goToPage('"+i+"')\">"+i+"</a>]";
                }
                else
                {
                  pager += "[width:20px;align:center\">" +
                         "<a href=\"#\" onclick=\"goToPage" +
                         "('"+i+"')\" >"+i+"</a>]";
                }
              }
              ddl_Pager.SelectedIndex = pageIndex;
              wr = new StringWriter();
              writer = new HtmlTextWriter(wr);
              ddl_Pager.RenderControl(writer);
              string pagerHtml = "<input type='button'" +
                                 " value='<' onclick='goToPrevPage()'>";
              pagerHtml += wr.ToString();
              pagerHtml += "<input type='button' value='>'" +
                           " onclick='this.disabled=goToNextPage()'>";
              wr.Close();
              writer.Close();
              return pager+pagerHtml+"<br>"+gridHtml;
            }
      }
}

上面的是Web服務,然後利用Ajax請求這個服務來擷取要現實的資料。以下是用戶端JavaScript代碼:

AjaxFuncs.js

//聲明非同步請求對象

/////////////////////////////////////////////////////////////////
var xmlhttp;
/////////////////////////////////////////////////////////////////
//填充DataGrid,這個函數有3個參數。

//第一個是包含DataGrid的DIV的ID

//第二個是查詢資料的sql語句

//第三個是要擷取第幾頁資料

/////////////////////////////////////////////////////////////////
var ph;
var fillGrid_Str_SQL="";
var currentPageIndex ;
function fillGrid(myPH,str_Sql,pageIndex){
      ph = window.document.getElementById(myPH);
      fillGrid_Str_SQL = str_Sql;
      currentPageIndex = pageIndex;
      var url = "http://localhost/GenricAjaxWS/GenricAjaxWS" +
                ".asmx/getGrid?sqlStr="+str_Sql+
                "&pageIndex="+pageIndex;

      if(window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
        xmlhttp.onreadystatechange=fillGrid_Change;
        xmlhttp.open("GET",url,true);
        xmlhttp.send(null);
    }
    //code for IE
    else if (window.ActiveXObject)
        {
        try
            {
            xmlhttp= new ActiveXObject("Msxml2.XMLHTTP");
            }
        catch(e)
            {
            try
            {
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(e){}
        }

        if(xmlhttp)
        {
            try
            {
            xmlhttp.onreadystatechange=fillGrid_Change;
            xmlhttp.open("GET",url,false);
            xmlhttp.send();
            }
            catch(e){}
        }
    }
}

function fillGrid_Change()
{
      if(xmlhttp.readyState==4&&xmlhttp.status==200)
      {
          //var rows=xmlhttp.responseXML.
          //        selectNodes(".//TahaSchema//TahaTable");
          var row =   xmlhttp.responseXML.selectNodes(".//");
          ph.innerHTML = row[1].text;
      }
}

function goToPage(pageIndex){
      fillGrid(ph.id,fillGrid_Str_SQL,pageIndex)
}
 
function goToNextPage(){
      try{ 
            fillGrid(ph.id,fillGrid_Str_SQL,
                     parseInt(currentPageIndex)+1);
            return false;
      }
      catch(e){
            return true;
      }
}

function goToPrevPage(){
      fillGrid(ph.id,fillGrid_Str_SQL,
               parseInt(currentPageIndex)-1)
}

最後就是顯示資料的html頁面,執行個體代碼如下:

AjaxGrid.html:

<html>
  <head>
    <title>AjaxGrid</title>
  <script language="javascript"
        type="text/javascript" src="ajaxFuncs.js"></script>
  </head>
  <body  onload="fillGrid('myPH','select * from sales',1)">
           
    <form id="Form1" method="post" runat="server">
                        <div id="myPH" ></div>
     </form>
  </body>
</html>

到此利用Ajax實現DataGrid無重新整理分頁就完成了。

希望對您有用!

歡迎大家討論,您如果還有更好的方法或意見,請您留言,讓我們共同做的更好。

謝謝您瀏覽我的Blog!

http://blog.csdn.net/soarheaven/archive/2006/09/24/1270120.aspx

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.