GridView的数据显示一般是固定的,假如要像Ajax那样实现GridView数据动态更新而不刷新页面,就有些难度了.客户提出的需求,没办法,也得去试着想办法实现.
涉及到Asp.Net事件机制的实现"_doPostback".Asp.Net的底层封装了XMLHttpRequest异步请求对象.在WebResource.axd中可以查看到这些封装的JavaScript.对于页面的异步请求,我们需要实现ICallbackEventHandler接口,并显示实现其中的GetCallbackResult()和RaiseCallbackEvent()这两个方法.废话不多少,假如了解Asp.Net机制的话一看就明白了.代码就贴在下面:
后台代码:
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Globalization;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page, System.Web.UI.ICallbackEventHandler
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Bind();
}
string cbReference = Page.ClientScript.GetCallbackEventReference(Page, "", "Refresh", "");
btnGet.Attributes.Add("onclick", cbReference);
string script = "";
script += "<script>/r/n";
script += "function Refresh(DataFromServer){/r/n";
script += "document.getElementById('Result').innerHTML=DataFromServer;/r/n";
script += "}/r/n</script>/r/n";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Refresh", script);
}
public string GetCallbackResult()
{
//return RenderControl(Test);
return RenderControl(Test);
}
public void RaiseCallbackEvent(string eventArgument)
{
Bind();
}
private string RenderControl(Control c)
{
StringWriter writer1 = new StringWriter(CultureInfo.InvariantCulture);
HtmlTextWriter writer = new HtmlTextWriter(writer1);
c.RenderControl(writer);
writer.Flush();
writer.Close();
return writer1.ToString();
}
#region 数据绑定
public void Bind()
{
// 获取链接
SqlConnection conn = new SqlConnection();
// 设置连接的数据库
string str = "server=localhost;database=northwind;Integrated Security=True";
conn.ConnectionString = str;
// sql语句
string strSql = "SELECT EMPLOYEES.EMPLOYEEID, EMPLOYEES.FIRSTNAME, EMPLOYEES.LASTNAME, EMPLOYEES.TITLE FROM EMPLOYEES";
// 获取SqlDataAdapter对象
SqlDataAdapter adapter = new SqlDataAdapter(strSql, conn);
// 声明DataSet对象
DataSet ds = new DataSet();
// 填充DataSet
adapter.Fill(ds);
// 数据绑定
Test.DataSource = ds;
Test.DataBind();
}
#endregion
}
前台:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<input type="button" runat="server" id="btnGet" value="Get" style="display:none"/>
<div id="Result">
<asp:GridView ID="Test" runat="server" CellPadding="4" ForeColor="#333333">
</asp:GridView>
</div>
</form>
<script type="text/javascript">function btnclick(){document.getElementById("btnGet").click();}setInterval("btnclick()",10000);</script>
</body>
</html>
程序中用到的数据库是Sql Server的示例数据库:northwind。