如何使 GridView 自动部分更新,类似 Gmail 收件箱






4.58/5 (9投票s)
本文展示了如何使用 jQuery Ajax/get 方法向 gridView 添加新的数据库行(在页面加载后插入),而无需像 Gmail 收件箱收到新邮件时那样刷新页面

引言
本文介绍了一种将数据库中的新行添加到 gridview 而无需刷新页面的方法。当客户端希望查看新行(例如,新邮件)而无需刷新页面时,这非常有用。
如果您想观看实时演示,请登录您的 Gmail 帐户(加载标准 Gmail),然后从其他浏览器向您的 Gmail 地址发送邮件,您会看到您的 Gmail 收件箱会自动将新邮件的行添加到您的邮件gridView
。
有一种快速显示新行的方法:将 GridView
放入 updatePanel
中,并每 3 秒(或任何时间)刷新 updatePanel
,但这会增加页面源代码的大小和页面加载时间......
但在本文中,我们将学习一种方法,通过 JavaScript 超时从服务器(通过 jQuery get 方法)自动获取新行,然后将这些新行添加到 gridView
(通过 jQuery HTML 操作)。
背景
你应该知道
- jQuery HTML 操作 - 您可以从 w3schools.com 学习
- jQuery 和 Ajax - 您可以从 w3schools.com 学习
Using the Code
假设我们想要一个 gridView
,它能够自动将数据库中的新行添加到其中,我们按照以下步骤操作,以获得一个像 Gmail 收件箱一样的 perl gridView
!
步骤 1
将以下 JavaScript 代码添加到包含您的 gridView
的页面
<script type="text/javascript" src="jquery-1.4.js"></script>
<script type="text/javascript" src="jquery.cookie.js"></script>
<script type="text/javascript">
var jq = jQuery.noConflict();
f1();
function f1() {
jq(document).ready(function() {
var lastid = jq.cookie("maxletterid");
if (lastid != "0") // if gridView already have any rows
// so in the cookie is a row-id that is not equal
// to zero (the cookie initially set by Page_Init
// method of the current page having the gridView)
jq.get("test2.aspx", function(dataReturned) {
if (dataReturned != "") //if there are new rows in database
//for adding to the gridView
{
//jq('#<%=gvLetters.ClientID %>').prepend(dataReturned); //for
// <asp:gridview showheader="False" ... />
jq('#<%=gvLetters.ClientID %>
tr:first').after(dataReturned); //for <asp:gridview
//showheader="True" ... />
}
window.setTimeout("f1()", 1000); // gridView will be
// updated every 1000 ms(1 second)
});
else
jq.get("test2.aspx", function(dataReturned) {
if (dataReturned != "") //if there are new rows in database
//for adding to the gridView
{
jq('#<%=gvLetters.ClientID %>').html(dataReturned);
}
window.setTimeout("f1()", 1000); // for calling function f1()
// every 1000 milliseconds(1 second)
});
});
}
由于上面的代码使用了 jQuery 技术,请注意不要忘记将 *jquery-1.4.js* 和 *jquery.cookie.js* 文件(与 jQuery 本身及其 cookie 插件相关)复制到您的网站目录。
在上面的代码中:
- 将
gvLetters
替换为您的gridView
控件的 id - 将 *test2.aspx* 替换为您的 aspx 或 ashx 页面的名称,该页面从数据库获取新行并将它们发送回客户端(显示给客户端的具有
gridView
的当前页面)
如果您希望每 [x : x != 1000] 毫秒向服务器发送请求(以获取要添加到gridView
的新行),请更改window.setTimeout
函数中的 1000
第二步
将以下 C# 代码添加到包含您的 gridView
的页面的 codeBehind (*.aspx.cs*)
protected void Page_Init(object sender, EventArgs e)
{
HttpCookie c1 = new HttpCookie("maxletterid", getMaxLetterId().ToString());
Response.Cookies.Add(c1);
}
public static int getMaxLetterId()
{
int maxLetterId = 0;
SqlConnection sqlc1 = new SqlConnection
("Data Source=kazem-pc;Initial Catalog=test1;Integrated Security=True");
string strcommand1 = "SELECT max(id) from tblTest";
SqlCommand sqlcommand1 = new SqlCommand(strcommand1, sqlc1);
SqlDataReader sqldr1 = null;
try
{
sqlc1.Open();
sqldr1 = sqlcommand1.ExecuteReader();
while (sqldr1.Read())
{
maxLetterId = Convert.ToInt32(sqldr1[0]);
}
sqlc1.Close();
}
catch (Exception e1)
{
if (sqlc1.State == ConnectionState.Open)
sqlc1.Close();
}
return maxLetterId;
}
在上面的代码中:
- 将
test1
在Initial Catalog=test1;
中替换为您的 SQL Server 数据库的名称 - 将
id
在SELECT max(id) from tblTest
中替换为您的数据库表中 [id] 列的名称(您的gridView
绑定到的表) - 该表的第一列通常是主键,在创建表时已识别出标识规范 - 将
tblTest
在SELECT max(id) from tblTest
中替换为您的数据库表的名称(您的gridView
绑定到的表)
步骤 3
将以下 C# 代码添加到第二个页面的 codeBehind (*.aspx.cs*)(负责获取客户端的请求,然后从数据库获取新行并将它们发送回客户端的页面)。
protected void Page_Load(object sender, EventArgs e)
{
string strReturn = string.Empty;
int intfirstRead = 0;
int lastoldid = Convert.ToInt32(Request.Cookies["maxletterid"].Value);
// you can change the following two commands to adjust with your dataBase, table
SqlConnection sqlc1 = new SqlConnection("Data Source=kazem-pc;
Initial Catalog=test1;Integrated Security=True");
string strcommand1 = "SELECT * FROM [tblTest] where id >
" + lastoldid.ToString() +" order by id desc";
SqlCommand sqlcommand1 = new SqlCommand(strcommand1, sqlc1);
SqlDataReader sqldr1 = null;
try
{
sqlc1.Open();
sqldr1 = sqlcommand1.ExecuteReader();
if (sqldr1.HasRows)
{
intfirstRead = 0;
while (sqldr1.Read())
{
//-------------------------------------------------------------------
//the following 'if' block is when <asp:GridView ShowHeader="
//true" .../> in page "test1.aspx", so please comment
//this 'if' when <asp:GridView ShowHeader="false" .../>
if ((lastoldid == 0) && (intfirstRead == 0))
{
strReturn = "<tr style=\"color:White;
background-color:#5D7B9D;font-weight:bold;\">";
for (int k = 0; k < sqldr1.FieldCount; k++)
strReturn += "<th scope=\"col\">" +
sqldr1.GetName(k) + "</th>";
strReturn += "</tr>";
intfirstRead = 1;
}
//-------------------------------------------------------------------
strReturn += "<tr style=\"background-color:#D6E0ED;
font-style:italic;font-weight:bold;\">";
for (int j = 0; j < sqldr1.FieldCount; j++)
strReturn += "<td>" + sqldr1[j].ToString() + "</td>";
//strReturn += "<td>"+sqldr1["letterid"].ToString()+
"</td><td>"+sqldr1["subject"].ToString()+"</td>";
strReturn += "</tr>";
}
HttpCookie c1 = new HttpCookie
("maxletterid", getMaxLetterId().ToString());
Response.Cookies.Add(c1);
}
sqlc1.Close();
}
catch (Exception e1)
{
if (sqlc1.State == ConnectionState.Open)
sqlc1.Close();
strReturn = e1.Message;
}
Response.Expires = -1;
Response.ContentType = "text/plain";
Response.Write(strReturn);
Response.End();
}
public static int getMaxLetterId()
{
int maxLetterId = 0;
SqlConnection sqlc1 = new SqlConnection("Data Source=kazem-pc;
Initial Catalog=test1;Integrated Security=True");
string strcommand1 = "SELECT max(id) from tblTest";
SqlCommand sqlcommand1 = new SqlCommand(strcommand1, sqlc1);
SqlDataReader sqldr1 = null;
try
{
sqlc1.Open();
sqldr1 = sqlcommand1.ExecuteReader();
while (sqldr1.Read())
{
maxLetterId = Convert.ToInt32(sqldr1[0]);
}
sqlc1.Close();
}
catch (Exception e1)
{
if (sqlc1.State == ConnectionState.Open)
sqlc1.Close();
}
return maxLetterId;
}
在上面的代码中:
- 如上所述,对于前面的代码,替换
test1
、id
、tblTest
- 在 *test1.aspx* 中,使用您的数据库和表名更正
<asp:SqlDataSource ID="SqlDataSource1" .... > ConnectionString
和SelectCommand
的值
现在您已准备好查看自动添加的 gridView
,只需创建一个插入页面(如 *insert.aspx*)以插入到您的表中,然后同时浏览 *test1.aspx* 和您的插入页面,然后插入到您的数据库中,同时查看新行将添加到您的 gridView
中......... 我正在等待您将想法发送到我的邮件.......
运行您从本文以上链接下载的演示
请先阅读 *ReadMe.txt*。此文件包含在您从本文顶部链接下载的 zip 文件中。