正文
一、效果图
二、代码实现
2.1 客户端
tablepage.aspx
代码
Ext.onReady(function() {
Ext.QuickTips.init();
Ext.form.Field.prototype.msgTarget = 'side';
//搜索id
var id = new NumberField('tbSearch');
id.style='text-align:center';//设置文本居中
var store = new Ext.data.Store({
proxy: new Ext.data.HttpProxy({
url: 'tablepage.aspx?method=search',
method: 'GET'
}),
reader: new Ext.data.JsonReader({
totalProperty: 'count',
root: 'result'
}, [
{ name: 'Name' },
{ name: 'Id' },
{ name: 'Email' },
{ name: 'Gender' }
]),
baseParams:{
id : '', //用于分页时保存搜索条件
limit: 10 //每页显示数量
}
});
//加载数据
store.load();
//遍历数据
// store.each(function(record) {
// alert(record.get('name'));
// });
// for (var i = 0; i < store.getCount(); i++) {
// var record = store.getAt(i);
// alert(record.get('name'));
// }
var dataColumns = new Ext.grid.ColumnModel({
columns: [
new Ext.grid.RowNumberer(), //显示行号
{ header: "编 号", dataIndex: 'Id', sortable: true },
{ header: "名 称", dataIndex: 'Name' },
{ header: "邮 箱", dataIndex: 'Email' },
{ header: "性 别", dataIndex: 'Gender' }
],
defaults: {
align: 'center'
}
});
var grid = new Ext.grid.GridPanel({
store: store,
cm: dataColumns, //columns: [{}]
renderTo: Ext.getBody(),
//autoExpandColumn: 1,
title: '<center style="curor:hand" onclick="window.location.reload();">搜索与分页</center>',
autoScroll: true,
autoHeight: true,
border: true,
disableSelection: true,
enableHdMenu:false,
frame: true,
loadMask: { msg: '正在加载数据,请稍侯……' }, //loadMask: true,
stripeRows: true, //隔行显示不同颜色
// bodyStyle:'width:99.8%',
// autoWidth:true,
width: 800,
//设置单行选中模式
selModel: new Ext.grid.RowSelectionModel({ singleSelect: false }),
//使列自动均分
viewConfig: {
forceFit: true
},
//搜索条
tbar: new Ext.Toolbar({
items:[
new Ext.form.Label({ text:'编号: ' }),
id,{
iconCls: "add", text: '搜索',
handler:function(){
//注意 sum 需要等数据加载完毕才能计算出来,不然始终为0
//alert(store.sum('Id'));
grid.store.baseParams['id'] = id.getValue();//防止分页时丢失
grid.store.reload();
}
}
]
}),
//底部分页工具条
bbar: new Ext.PagingToolbar({
pageSize: 10,//此处应与limit一致
store: store,
displayInfo: true,
emptyMsg: '没有记录'
})
});
});
Ext.QuickTips.init();
Ext.form.Field.prototype.msgTarget = 'side';
//搜索id
var id = new NumberField('tbSearch');
id.style='text-align:center';//设置文本居中
var store = new Ext.data.Store({
proxy: new Ext.data.HttpProxy({
url: 'tablepage.aspx?method=search',
method: 'GET'
}),
reader: new Ext.data.JsonReader({
totalProperty: 'count',
root: 'result'
}, [
{ name: 'Name' },
{ name: 'Id' },
{ name: 'Email' },
{ name: 'Gender' }
]),
baseParams:{
id : '', //用于分页时保存搜索条件
limit: 10 //每页显示数量
}
});
//加载数据
store.load();
//遍历数据
// store.each(function(record) {
// alert(record.get('name'));
// });
// for (var i = 0; i < store.getCount(); i++) {
// var record = store.getAt(i);
// alert(record.get('name'));
// }
var dataColumns = new Ext.grid.ColumnModel({
columns: [
new Ext.grid.RowNumberer(), //显示行号
{ header: "编 号", dataIndex: 'Id', sortable: true },
{ header: "名 称", dataIndex: 'Name' },
{ header: "邮 箱", dataIndex: 'Email' },
{ header: "性 别", dataIndex: 'Gender' }
],
defaults: {
align: 'center'
}
});
var grid = new Ext.grid.GridPanel({
store: store,
cm: dataColumns, //columns: [{}]
renderTo: Ext.getBody(),
//autoExpandColumn: 1,
title: '<center style="curor:hand" onclick="window.location.reload();">搜索与分页</center>',
autoScroll: true,
autoHeight: true,
border: true,
disableSelection: true,
enableHdMenu:false,
frame: true,
loadMask: { msg: '正在加载数据,请稍侯……' }, //loadMask: true,
stripeRows: true, //隔行显示不同颜色
// bodyStyle:'width:99.8%',
// autoWidth:true,
width: 800,
//设置单行选中模式
selModel: new Ext.grid.RowSelectionModel({ singleSelect: false }),
//使列自动均分
viewConfig: {
forceFit: true
},
//搜索条
tbar: new Ext.Toolbar({
items:[
new Ext.form.Label({ text:'编号: ' }),
id,{
iconCls: "add", text: '搜索',
handler:function(){
//注意 sum 需要等数据加载完毕才能计算出来,不然始终为0
//alert(store.sum('Id'));
grid.store.baseParams['id'] = id.getValue();//防止分页时丢失
grid.store.reload();
}
}
]
}),
//底部分页工具条
bbar: new Ext.PagingToolbar({
pageSize: 10,//此处应与limit一致
store: store,
displayInfo: true,
emptyMsg: '没有记录'
})
});
});
代码说明:
实现了非常简单搜索和分页,需要注意的是关于搜索分页时搜索结果丢失的问题,这里采取了两个步骤:先是在Ext.data.Store的baseParams中声明搜索传值变量,然后再点击搜索按钮时将搜索条件存入到baseParams里,这样分页时条件可以保持下来。
2.2 服务端
tablepage.aspx.cs
代码
public override string Search()
{
int start = -1;
int.TryParse(Request.QueryString["start"], out start);
int limit = -1;
int.TryParse(Request.QueryString["limit"], out limit);
string id = Request.QueryString["id"];
IList<User> result = new List<User>();
if (string.IsNullOrEmpty(id))
result = GetPage(ConverToList(dataSource.Values), start, limit);
else
{
int uid;
if (int.TryParse(id, out uid))
{
if (dataSource.ContainsKey(uid))
result.Add(dataSource[uid]);
}
}
return new StringBuilder().Append("{count:")
.Append(1000)
.Append(",result:")
.Append(JavaScriptConvert.SerializeObject(result))
.Append('}')
.ToString();
}
#region 数据源
private static IDictionary<int, User> dataSource = new Dictionary<int, User>();
static tablepage()
{
for (int i = 0; i < 1000; i++)
{
User user = BuildUser(i);
dataSource.Add(user.Id, user);
}
}
private static IList<User> GetPage(IList<User> data, int start, int limit)
{
IList<User> result = new List<User>();
int length = start + limit;
if (length > data.Count)
length = data.Count;
for (int i = start; i < length; i++)
{
result.Add(data[i]);
}
return result;
}
private static IList<User> ConverToList(ICollection<User> users)
{
User[] result = new User[users.Count];
users.CopyTo(result, 0);
return result;
}
private static User BuildUser(int number)
{
return new User()
{
Id = number,
Email = string.Format("test{0}163.com", number),
Name = string.Format("test{0}", number),
Gender = new Random().Next(2)
};
}
class User
{
/// <summary>
/// 编号
/// </summary>
public int Id { get; set; }
/// <summary>
/// 邮箱
/// </summary>
public string Email { get; set; }
/// <summary>
/// 名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 性别 0 女 1 男
/// </summary>
public int Gender { get; set; }
}
#endregion
{
int start = -1;
int.TryParse(Request.QueryString["start"], out start);
int limit = -1;
int.TryParse(Request.QueryString["limit"], out limit);
string id = Request.QueryString["id"];
IList<User> result = new List<User>();
if (string.IsNullOrEmpty(id))
result = GetPage(ConverToList(dataSource.Values), start, limit);
else
{
int uid;
if (int.TryParse(id, out uid))
{
if (dataSource.ContainsKey(uid))
result.Add(dataSource[uid]);
}
}
return new StringBuilder().Append("{count:")
.Append(1000)
.Append(",result:")
.Append(JavaScriptConvert.SerializeObject(result))
.Append('}')
.ToString();
}
#region 数据源
private static IDictionary<int, User> dataSource = new Dictionary<int, User>();
static tablepage()
{
for (int i = 0; i < 1000; i++)
{
User user = BuildUser(i);
dataSource.Add(user.Id, user);
}
}
private static IList<User> GetPage(IList<User> data, int start, int limit)
{
IList<User> result = new List<User>();
int length = start + limit;
if (length > data.Count)
length = data.Count;
for (int i = start; i < length; i++)
{
result.Add(data[i]);
}
return result;
}
private static IList<User> ConverToList(ICollection<User> users)
{
User[] result = new User[users.Count];
users.CopyTo(result, 0);
return result;
}
private static User BuildUser(int number)
{
return new User()
{
Id = number,
Email = string.Format("test{0}163.com", number),
Name = string.Format("test{0}", number),
Gender = new Random().Next(2)
};
}
class User
{
/// <summary>
/// 编号
/// </summary>
public int Id { get; set; }
/// <summary>
/// 邮箱
/// </summary>
public string Email { get; set; }
/// <summary>
/// 名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 性别 0 女 1 男
/// </summary>
public int Gender { get; set; }
}
#endregion
代码说明:
这里仍然没有连接数据库,模拟数据与分页查询。
2.3 存储过程
代码
CREATE PROCEDURE dbo.DataPager
(
@StartIndex INT = 0 ,
@Limit INT = 15,
@RowsCount INT = 0 OUTPUT, -- 输出记录总行数
@SQLString VARCHAR(500)
)
AS
SET NOCOUNT ON
SELECT IDENTITY(INT,1,1) AS [NewID],* INTO #TMP_ZSFLZ1 FROM [TB_XJYJZ] WHERE 1=2
INSERT INTO #TMP_ZSFLZ1 EXEC sp_executesql @SQLString
--总行数
SELECT @RowsCount = COUNT([NewID]) FROM #TMP_ZSFLZ
SET @StartIndex = @StartIndex + 1
SELECT * FROM #TMP_ZSFLZ tz
WHERE [NewID] BETWEEN @StartIndex AND @StartIndex + @Limit - 1
DROP TABLE #TMP_ZSFLZ
RETURN
GO
(
@StartIndex INT = 0 ,
@Limit INT = 15,
@RowsCount INT = 0 OUTPUT, -- 输出记录总行数
@SQLString VARCHAR(500)
)
AS
SET NOCOUNT ON
SELECT IDENTITY(INT,1,1) AS [NewID],* INTO #TMP_ZSFLZ1 FROM [TB_XJYJZ] WHERE 1=2
INSERT INTO #TMP_ZSFLZ1 EXEC sp_executesql @SQLString
--总行数
SELECT @RowsCount = COUNT([NewID]) FROM #TMP_ZSFLZ
SET @StartIndex = @StartIndex + 1
SELECT * FROM #TMP_ZSFLZ tz
WHERE [NewID] BETWEEN @StartIndex AND @StartIndex + @Limit - 1
DROP TABLE #TMP_ZSFLZ
RETURN
GO
代码说明:
虽然本文没有用到,倒是实际中肯定要用到的,这里写一个样例,仅供参考(注意:这里是SQL2000的例子)。
本文转自over140 51CTO博客,原文链接:http://blog.51cto.com/over140/586541,如需转载请自行联系原作者