简单介绍:
本示例主要用EXT2.2+vs.2008.net+C#+sql Server 2005实现在GridPanel上单击右键显示菜单,在单击某个菜单项后弹出一个窗口用于处理具体的操作
功能:
1,生成GridPanel
2,在GridPanel上单击右键显示菜单
3,实现分页
环境:
1,EXT2.2版本
2,vs.net2008+C#
3,sql Server 2005
说明:项目所需要的具体文件以及后台文件都可以在前面的2个例子中下载
对行数据的编辑没有具体实现,仅仅是展示如何单击右键显示菜单并且弹出相应的窗口,没有对具体的数据后台处理
截图:
1,在某行上点击右键,出现下图所示的菜单
2,在菜单上点某个菜单项后出现下图所示的窗口
Code
下面是源代码
1,页面文件:Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="GridPanel_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>
<link rel="stylesheet" type="text/css" href="resources/css/ext-all.css"/>
<script type="text/javascript" src="ExtBase/ext-base.js"></script>
<script type="text/javascript" src="ExtBase/ext-all.js"></script>
<script type="text/javascript" src="ExtBase/ext-lang-zh_CN.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="panel_id"></div>
<script type="text/javascript">
var grid;
function DataGrid()
{
var cm = new Ext.grid.ColumnModel
([
{header: "编号", 120, dataIndex: 'ID', sortable: true},
{header: "标题", 180, dataIndex: 'Title', sortable: true},
{header: "作者", 115, dataIndex: 'Author', sortable: true},
{header: "来源", 100, dataIndex: 'Source', sortable: true},
{header: "日期", 100, dataIndex: 'PostDate', sortable: true}
]);
var titleInfo = "编辑数据";
var fields = [{name:"ID"},{name:"Title"},{name:"Author"},{name:"Source"},{name:"PostDate"}];
var newStore = new Ext.data.Store
({
proxy:new Ext.data.HttpProxy({url:"JsonData.aspx?param=initData"}),
reader:new Ext.data.JsonReader({totalProperty:"totalPorperty",root:"result",fields:fields})
});
newStore.load({params:{start:0,limit:16}});
var pagingBar = new Ext.PagingToolbar
({
displayInfo:true,
emptyMsg:"没有数据显示",
displayMsg:"显示从{0}条数据到{1}条数据,共{2}条数据",
store:newStore,
pageSize:16
});
this.gridPanel = new Ext.grid.GridPanel
({
cm:cm,
id:"grid_panel",
title:titleInfo,
store:newStore,
frame:false,
border:true,
layout:"fit",
pageSize:16,
autoWidth:true,
height:400,
clicksToEdit:1,
viewConfig:{forceFit:true},
bbar:pagingBar
});
this.gridPanel.on("rowcontextmenu",open_rowcontextmenu);
}
function open_rowcontextmenu(grid,rowIndex,e)
{
e.preventDefault();
var menus = new Ext.menu.Menu
([
{
xtype:"button",text:"编辑",pressed:true,icon:"imgMenus/3.png",
handler:function(){Edit(grid,rowIndex,e ,"编辑");}
},
{
xtype:"button",text:"删除",pressed:true,icon:"imgMenus/3.png",
handler:function(){Edit(grid,rowIndex,e ,"删除");}
}
]);
menus.showAt(e.getPoint());
}
function Edit(grid,rowIndex,e,titleInfo)
{
var record = grid.getStore().getAt(rowIndex);
var currID = record.data.ID;
var currAuthor = record.data.Author;
var currTitle = record.data.Title;
var currSource = record.data.Source;
var currPostDate = record.data.PostDate;
var p = new Ext.FormPanel
({
frame:true,labelWidth:36,
items:
[
{xtype:"hidden",id:"ID",201,value:currID},
{xtype:"textfield",fieldLabel:"标题",id:"Title",201,value:currTitle},
{xtype:"textfield",fieldLabel:"作者",id:"Author",200,value:currAuthor},
{xtype:"textfield",fieldLabel:"来源",id:"Source",201,value:currSource},
{xtype:"datefield",fieldLabel:"日期",id:"PostDate",201,value:currPostDate,format:"Y年m月d日"}
]
});
var win = new Ext.Window
({
title:titleInfo+"窗口",autoHeight:true,300,resizable:false,buttonAlign:"center", modal:true,//height:300,
items:[p],
bbar:
[
{xtype:"button",text:"确定"+titleInfo,handler:function(){Edit_Sub(win,titleInfo);}},
'','',
{xtype:"button",text:"关闭",handler:function(){win.destroy();}}
]
});
win.show();
}
function Edit_Sub(winParam,titleInfo)
{
var currID = Ext.getCmp("ID").getValue();
winParam.destroy();
if(titleInfo=="删除")
{
Ext.Msg.alert("消息提示","删除成功");
//具体删除代码自己实现
}
else
{
Ext.Msg.alert("消息提示","编辑成功");
//具体修改代码自己实现
}
}
function MakePanel(obj)
{
this.panel_def = new Ext.Panel
({
layout:"fit",
border:true,
frame:true,
title:"数据浏览",
autoWidth:true,
height:500,
id:"Viewport_ID",
renderTo:"panel_id",
items:[obj.gridPanel]
});
}
function loader()
{
Ext.QuickTips.init();
grid = new DataGrid();
MakePanel(grid);
}
Ext.onReady(loader);
</script>
</div>
</form>
</body>
</html>
2,后台cs文件:JsonData.aspx.cs
using Newtonsoft.Json;
public partial class GridPanel_JsonData : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
分页参数#region 分页参数
int pagesize = 5;
int start = 1;
string field, asc_desc;
if (string.IsNullOrEmpty(Request["sort"]))
{
field = "ID";
asc_desc = "ASC";
}
else
{
field = Request["sort"];
asc_desc = Request["dir"];
}
if (!string.IsNullOrEmpty(Request["limit"]))
{
pagesize = int.Parse(Request["limit"]);
start = int.Parse(Request["start"]);
}
start = start / pagesize;
start += 1;
#endregion
string param = Convert.ToString(Request["param"]);
if (param == "initData")
{
Bind_Data(field, asc_desc, pagesize, start, "ceshitwo");
}
}
private void Bind_Data(string field, string asc_desc, int pagesize, int start, string tableName)
{
DataSet ds = Business.GetPagingData(field, asc_desc, pagesize, start, tableName);
if (ds != null && ds.Tables[0].Rows.Count > 0)
{
GetJsonData(ds);
}
else
{
Response.Write("");
}
}
private void GetJsonData(DataSet ds)
{
List<Hashtable> hashList = new List<Hashtable>();
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
DataRow row = ds.Tables[0].Rows[i] as DataRow;
Hashtable ht = new Hashtable();
foreach (DataColumn col in ds.Tables[0].Columns)
{
ht.Add(col.ColumnName, row[col.ColumnName]);
}
hashList.Add(ht);
}
int? count = Access.GetCount("Select count(*) from ceshitwo");
string json = "{totalPorperty:" + count + ",result:" + JavaScriptConvert.SerializeObject(hashList) + "}";
Response.Write(json);
}
}
<三>分页功能单独实现
public class Business
{
public static DataSet GetPagingData(string field, string asc_desc, int pagesize, int start,string tableName)
{
string sql = "WITH MOVIES AS ( " +
" SELECT ROW_NUMBER() OVER " +
" (ORDER BY " + field + " " + asc_desc + " ) AS Row," +
" *" +
" FROM " + tableName + " )" +
" SELECT *" +
" FROM MOVIES " +
" WHERE Row between (@start-1)* @pagesize+1 and @start*@pagesize";
SqlParameter[] prams =
{
new SqlParameter("@start",start),
new SqlParameter("@pagesize",pagesize)
};
return Access.GetDataSet(sql, prams);
}
}
<四>数据库访问层:
public class Access
{
public Access()
{ }
public static string connstring = "";
private static void CreateCommand(SqlConnection conn, SqlCommand cmd, string cmdText, params SqlParameter[] prams)
{
conn.ConnectionString = Access.connstring;
if (conn.State == ConnectionState.Closed)
conn.Open();
cmd.Connection = conn;
cmd.CommandText = cmdText;
if (prams != null)
{
foreach (SqlParameter p in prams)
cmd.Parameters.Add(p);
}
}
public static DataSet GetDataSet(string cmdText)
{
return GetDataSet(cmdText,null);
}
public static DataSet GetDataSet(string cmdText, params SqlParameter[] prams)
{
using (SqlConnection conn = new SqlConnection())
{
SqlCommand cmd = new SqlCommand();
CreateCommand(conn, cmd, cmdText, prams);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
cmd.Parameters.Clear();
return ds;
}
}
public static int? GetCount(string cmdText)
{
return GetCount(cmdText, null);
}
public static int? GetCount(string cmdText,params SqlParameter[] prams)
{
using (SqlConnection conn = new SqlConnection())
{
SqlCommand cmd = new SqlCommand();
CreateCommand(conn, cmd, cmdText, prams);
int? count;
count = Convert.ToInt32( cmd.ExecuteScalar() );
cmd.Parameters.Clear();
return count;
}
}
}
说明:数据表可以使用以下语句生成即可
USE [Test]
GO
/**//****** 对象: Table [dbo].[ceshitwo] 脚本日期: 08/26/2008 13:04:59 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ceshitwo](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Title] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
[Author] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
[Source] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
[PostDate] [datetime] NULL CONSTRAINT [DF_ceshitwo_PostDate] DEFAULT (getdate()),
CONSTRAINT [PK_ceshitwo] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
下面是源代码
1,页面文件:Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="GridPanel_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>
<link rel="stylesheet" type="text/css" href="resources/css/ext-all.css"/>
<script type="text/javascript" src="ExtBase/ext-base.js"></script>
<script type="text/javascript" src="ExtBase/ext-all.js"></script>
<script type="text/javascript" src="ExtBase/ext-lang-zh_CN.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="panel_id"></div>
<script type="text/javascript">
var grid;
function DataGrid()
{
var cm = new Ext.grid.ColumnModel
([
{header: "编号", 120, dataIndex: 'ID', sortable: true},
{header: "标题", 180, dataIndex: 'Title', sortable: true},
{header: "作者", 115, dataIndex: 'Author', sortable: true},
{header: "来源", 100, dataIndex: 'Source', sortable: true},
{header: "日期", 100, dataIndex: 'PostDate', sortable: true}
]);
var titleInfo = "编辑数据";
var fields = [{name:"ID"},{name:"Title"},{name:"Author"},{name:"Source"},{name:"PostDate"}];
var newStore = new Ext.data.Store
({
proxy:new Ext.data.HttpProxy({url:"JsonData.aspx?param=initData"}),
reader:new Ext.data.JsonReader({totalProperty:"totalPorperty",root:"result",fields:fields})
});
newStore.load({params:{start:0,limit:16}});
var pagingBar = new Ext.PagingToolbar
({
displayInfo:true,
emptyMsg:"没有数据显示",
displayMsg:"显示从{0}条数据到{1}条数据,共{2}条数据",
store:newStore,
pageSize:16
});
this.gridPanel = new Ext.grid.GridPanel
({
cm:cm,
id:"grid_panel",
title:titleInfo,
store:newStore,
frame:false,
border:true,
layout:"fit",
pageSize:16,
autoWidth:true,
height:400,
clicksToEdit:1,
viewConfig:{forceFit:true},
bbar:pagingBar
});
this.gridPanel.on("rowcontextmenu",open_rowcontextmenu);
}
function open_rowcontextmenu(grid,rowIndex,e)
{
e.preventDefault();
var menus = new Ext.menu.Menu
([
{
xtype:"button",text:"编辑",pressed:true,icon:"imgMenus/3.png",
handler:function(){Edit(grid,rowIndex,e ,"编辑");}
},
{
xtype:"button",text:"删除",pressed:true,icon:"imgMenus/3.png",
handler:function(){Edit(grid,rowIndex,e ,"删除");}
}
]);
menus.showAt(e.getPoint());
}
function Edit(grid,rowIndex,e,titleInfo)
{
var record = grid.getStore().getAt(rowIndex);
var currID = record.data.ID;
var currAuthor = record.data.Author;
var currTitle = record.data.Title;
var currSource = record.data.Source;
var currPostDate = record.data.PostDate;
var p = new Ext.FormPanel
({
frame:true,labelWidth:36,
items:
[
{xtype:"hidden",id:"ID",201,value:currID},
{xtype:"textfield",fieldLabel:"标题",id:"Title",201,value:currTitle},
{xtype:"textfield",fieldLabel:"作者",id:"Author",200,value:currAuthor},
{xtype:"textfield",fieldLabel:"来源",id:"Source",201,value:currSource},
{xtype:"datefield",fieldLabel:"日期",id:"PostDate",201,value:currPostDate,format:"Y年m月d日"}
]
});
var win = new Ext.Window
({
title:titleInfo+"窗口",autoHeight:true,300,resizable:false,buttonAlign:"center", modal:true,//height:300,
items:[p],
bbar:
[
{xtype:"button",text:"确定"+titleInfo,handler:function(){Edit_Sub(win,titleInfo);}},
'','',
{xtype:"button",text:"关闭",handler:function(){win.destroy();}}
]
});
win.show();
}
function Edit_Sub(winParam,titleInfo)
{
var currID = Ext.getCmp("ID").getValue();
winParam.destroy();
if(titleInfo=="删除")
{
Ext.Msg.alert("消息提示","删除成功");
//具体删除代码自己实现
}
else
{
Ext.Msg.alert("消息提示","编辑成功");
//具体修改代码自己实现
}
}
function MakePanel(obj)
{
this.panel_def = new Ext.Panel
({
layout:"fit",
border:true,
frame:true,
title:"数据浏览",
autoWidth:true,
height:500,
id:"Viewport_ID",
renderTo:"panel_id",
items:[obj.gridPanel]
});
}
function loader()
{
Ext.QuickTips.init();
grid = new DataGrid();
MakePanel(grid);
}
Ext.onReady(loader);
</script>
</div>
</form>
</body>
</html>
2,后台cs文件:JsonData.aspx.cs
using Newtonsoft.Json;
public partial class GridPanel_JsonData : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
分页参数#region 分页参数
int pagesize = 5;
int start = 1;
string field, asc_desc;
if (string.IsNullOrEmpty(Request["sort"]))
{
field = "ID";
asc_desc = "ASC";
}
else
{
field = Request["sort"];
asc_desc = Request["dir"];
}
if (!string.IsNullOrEmpty(Request["limit"]))
{
pagesize = int.Parse(Request["limit"]);
start = int.Parse(Request["start"]);
}
start = start / pagesize;
start += 1;
#endregion
string param = Convert.ToString(Request["param"]);
if (param == "initData")
{
Bind_Data(field, asc_desc, pagesize, start, "ceshitwo");
}
}
private void Bind_Data(string field, string asc_desc, int pagesize, int start, string tableName)
{
DataSet ds = Business.GetPagingData(field, asc_desc, pagesize, start, tableName);
if (ds != null && ds.Tables[0].Rows.Count > 0)
{
GetJsonData(ds);
}
else
{
Response.Write("");
}
}
private void GetJsonData(DataSet ds)
{
List<Hashtable> hashList = new List<Hashtable>();
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
DataRow row = ds.Tables[0].Rows[i] as DataRow;
Hashtable ht = new Hashtable();
foreach (DataColumn col in ds.Tables[0].Columns)
{
ht.Add(col.ColumnName, row[col.ColumnName]);
}
hashList.Add(ht);
}
int? count = Access.GetCount("Select count(*) from ceshitwo");
string json = "{totalPorperty:" + count + ",result:" + JavaScriptConvert.SerializeObject(hashList) + "}";
Response.Write(json);
}
}
<三>分页功能单独实现
public class Business
{
public static DataSet GetPagingData(string field, string asc_desc, int pagesize, int start,string tableName)
{
string sql = "WITH MOVIES AS ( " +
" SELECT ROW_NUMBER() OVER " +
" (ORDER BY " + field + " " + asc_desc + " ) AS Row," +
" *" +
" FROM " + tableName + " )" +
" SELECT *" +
" FROM MOVIES " +
" WHERE Row between (@start-1)* @pagesize+1 and @start*@pagesize";
SqlParameter[] prams =
{
new SqlParameter("@start",start),
new SqlParameter("@pagesize",pagesize)
};
return Access.GetDataSet(sql, prams);
}
}
<四>数据库访问层:
public class Access
{
public Access()
{ }
public static string connstring = "";
private static void CreateCommand(SqlConnection conn, SqlCommand cmd, string cmdText, params SqlParameter[] prams)
{
conn.ConnectionString = Access.connstring;
if (conn.State == ConnectionState.Closed)
conn.Open();
cmd.Connection = conn;
cmd.CommandText = cmdText;
if (prams != null)
{
foreach (SqlParameter p in prams)
cmd.Parameters.Add(p);
}
}
public static DataSet GetDataSet(string cmdText)
{
return GetDataSet(cmdText,null);
}
public static DataSet GetDataSet(string cmdText, params SqlParameter[] prams)
{
using (SqlConnection conn = new SqlConnection())
{
SqlCommand cmd = new SqlCommand();
CreateCommand(conn, cmd, cmdText, prams);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
cmd.Parameters.Clear();
return ds;
}
}
public static int? GetCount(string cmdText)
{
return GetCount(cmdText, null);
}
public static int? GetCount(string cmdText,params SqlParameter[] prams)
{
using (SqlConnection conn = new SqlConnection())
{
SqlCommand cmd = new SqlCommand();
CreateCommand(conn, cmd, cmdText, prams);
int? count;
count = Convert.ToInt32( cmd.ExecuteScalar() );
cmd.Parameters.Clear();
return count;
}
}
}
说明:数据表可以使用以下语句生成即可
USE [Test]
GO
/**//****** 对象: Table [dbo].[ceshitwo] 脚本日期: 08/26/2008 13:04:59 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ceshitwo](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Title] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
[Author] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
[Source] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
[PostDate] [datetime] NULL CONSTRAINT [DF_ceshitwo_PostDate] DEFAULT (getdate()),
CONSTRAINT [PK_ceshitwo] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]