做了一个示例,用户更新的数据保存在Session中,点击“更新数据源”按钮后将Session中的数据更新到数据库中,可以在 http://www.webdiyer.com/demo/editdatagrid.aspx 看到演示效果:
文件代码:
test.aspx
===========================>
<%@ Page Language="C#" Debug="True"%>
<%@Import Namespace="System.Data"%>
<%@ Import Namespace="System.Data.SqlClient" %>
<script language="C#" runat="server">
const string DataTableName="Employees";
SqlConnection conn;
SqlDataAdapter adapter;
void Page_Load(Object src, EventArgs e)
{
conn=new SqlConnection("server=(local);database=pubs;uid=sa;pwd=");
adapter=new SqlDataAdapter("select * from employees",conn);
if(!Page.IsPostBack){
BindData();
}
}
//绑定数据
void BindData(){
//先从Session中获取DataTable
DataTable table=(DataTable)Session[DataTableName];
//若Session中的DataTable不存在,则从数据库获取数据
if(table==null){
table=new DataTable();
adapter.Fill(table);
//将DataTable保存到Session中
SaveTableToSession(table);
table.Columns["id"].AutoIncrement=true;
}
grid.DataSource=table;
grid.DataBind();
}
void ChangePage(object src,DataGridPageChangedEventArgs e){
grid.CurrentPageIndex=e.NewPageIndex;
BindData();
}
void UpdateDataTable(object src,EventArgs e){
try{
DataTable table=GetTableFromSession();
string name;
byte age;
string address;
CheckBox ckdel;
for(int i=0;i<grid.Items.Count;i++){
DataGridItem dgitem=grid.Items[i];
int empId=(int)grid.DataKeys[dgitem.ItemIndex];
ckdel=dgitem.FindControl("delckb") as CheckBox;
name=((TextBox)dgitem.Cells[0].Controls[1]).Text;
age=byte.Parse(((TextBox)dgitem.Cells[1].Controls[1]).Text);
address=((TextBox)dgitem.Cells[2].Controls[1]).Text;
UpdateEmployee(table,empId,name,age,address,ckdel.Checked);
}
SaveTableToSession(table);
cancelbtn.Enabled=true;
int rowcount=0;
foreach(DataRow row in table.Rows){
if(row.RowState!=DataRowState.Deleted)
rowcount++;
}
if(Math.Ceiling(rowcount/5.0)==grid.CurrentPageIndex&&grid.CurrentPageIndex>0)
grid.CurrentPageIndex-=1;
BindData();
msglbl.Text="更新数据表成功!";
}
catch(Exception ex){
msglbl.Text="更新数据表失败,出现意外错误:"+ex.Message;
}
}
void UpdateEmployee(DataTable table,int id,string name,byte age,string address,bool isDelete){
for(int i=0;i<table.Rows.Count;i++){
DataRow row=table.Rows[i];
//如果选中了删除复选框,就直接就该行数据删除,不用再更新,否则更新该行数据
if(row!=null&&row.RowState!=DataRowState.Deleted){
if((int)row["id"]==id){
if(!isDelete){
row["name"]=name;
row["age"]=age;
row["address"]=address;
}
else
row.Delete();
}
}
}
msglbl.Text="更新数据表成功!";
}
void UpdateDataBase(object src,EventArgs e){
try{
DataTable table=GetTableFromSession();
SqlCommandBuilder cmdbd=new SqlCommandBuilder(adapter);
adapter.Update(table);
msglbl.Text="更新数据源成功!";
cancelbtn.Enabled=false;
}
catch(Exception ex){
msglbl.Text="更新数据源失败,出现意外错误:"+ex.Message;
}
BindData();
}
void CancelUpdate(object src,EventArgs e){
DataTable table=GetTableFromSession();
table.RejectChanges();
grid.CurrentPageIndex=0;
BindData();
cancelbtn.Enabled=false;
}
void AddNewEmployee(object src,DataGridCommandEventArgs e){
if(e.CommandName=="Add"){
try{
DataTable table=GetTableFromSession();
string name=((TextBox)e.Item.FindControl("newname")).Text;
byte age=byte.Parse(((TextBox)e.Item.FindControl("newage")).Text);
string address=((TextBox)e.Item.FindControl("newaddress")).Text;
DataRow row=table.NewRow();
row["name"]=name;
row["age"]=age;
row["address"]=address;
table.Rows.Add(row);
SaveTableToSession(table);
//重新绑定数据
BindData();
msglbl.Text="添加新记录成功!";
cancelbtn.Enabled=true;
}
catch(Exception ex){
msglbl.Text="未能添加新记录,出现意外错误:"+ex.Message;
}
}
}
//将DataTable保存到session中
void SaveTableToSession(DataTable table){
Session[DataTableName]=table;
}
//从Session中获取DataTable
DataTable GetTableFromSession(){
DataTable table=(DataTable)Session[DataTableName];
if(table!=null){
return table;
}
else{
msglbl.Text="未能从Session中获取数据,可能Session已超时,请刷新或重新打开当前页面!";
return null;
}
}
</script>
<html>
<head>
<title> Webdiyer制造:)</title>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="Webdiyer(http://www.webdiyer.com)">
</head>
<body>
<form runat="server">
<asp:DataGrid runat="server" id="grid" AutogenerateColumns=false DataKeyField="id" ShowFooter=true AllowPaging=true PageSize=5 OnPageIndexChanged="ChangePage" PagerStyle-Mode="numericpages" OnItemCommand="AddNewEmployee">
<Columns>
<asp:TemplateColumn HeaderText="姓名">
<ItemTemplate>
<asp:TextBox runat="server" id="name" Text='<%#DataBinder.Eval(Container.DataItem,"name")%>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox runat="server" id="newname"/>
</FooterTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="年龄">
<ItemTemplate>
<asp:TextBox runat="server" id="age" Text='<%#DataBinder.Eval(Container.DataItem,"age")%>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox runat="server" id="newage"/>
</FooterTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="住址">
<ItemTemplate>
<asp:TextBox runat="server" id="address" Text='<%#DataBinder.Eval(Container.DataItem,"address")%>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox runat="server" id="newaddress"/>
</FooterTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="删除">
<ItemTemplate>
<asp:CheckBox runat="server" id="delckb"/>
</ItemTemplate>
<FooterTemplate>
<asp:Button runat="server" Text="添加" CommandName="Add"/>
</FooterTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
<asp:Label runat="server" EnableViewState="false" id="msglbl" ForeColor="red"/>
<div>
<asp:Button runat="server" id="updatebtn" Text="更新数据表" OnClick="UpdateDataTable"/>
<asp:Button runat="server" id="cancelbtn" Text="取消对数据表的更新" Enabled=false OnClick="CancelUpdate"/>
<asp:Button runat="server" id="updatedbtbn" Text="更新数据源" OnClick="UpdateDataBase"/>
</div>
<div>
说明:DataGrid中的数据类型都没有进行验证,如果输入错误的数据类型或空值可能会出错,实际应用中应该对用户输入的数据进行验证!
</div>
</form>
</body>
</html>
数据库中employees表结构:
CREATE TABLE employees (
[id] [int] IDENTITY (1, 1) NOT NULL ,
[name] [nvarchar] (10) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[age] [tinyint] NOT NULL ,
[address] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL
) ON [PRIMARY]
GO
ALTER TABLE employees ADD
CONSTRAINT [PK_employees] PRIMARY KEY CLUSTERED
(
[id]
) ON [PRIMARY]
GO