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
Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=368601