使用DataList控件的编辑模板
控件设置:
<asp:DataList id="dlEditItem" runat="server" DataKeyField="EmployeeID">
<HeaderTemplate>
人员信息
</HeaderTemplate>
<FooterTemplate>
<hr color="red">
</FooterTemplate>
<ItemTemplate>
<asp:Button id="edit" runat="server" Text="编辑" CommandName="edit"></asp:Button>
<%#DataBinder.Eval(Container.DataItem,"LastName")%>
<%#DataBinder.Eval(Container.DataItem,"FirstName")%>
</ItemTemplate>
<EditItemTemplate>
<asp:Label Runat="server" ID="lastname">
<%#DataBinder.Eval(Container.DataItem,"LastName")%>
</asp:Label>
<asp:Label Runat="server" ID="FirstName">
<%#DataBinder.Eval(Container.DataItem,"FirstName")%>
</asp:Label>
<asp:TextBox Runat=server ID="Title" Text='<%#DataBinder.Eval(Container.DataItem,"Title")%>'/>
<asp:TextBox Runat=server ID="titleOfCourtesy" Text='<%#DataBinder.Eval(Container.DataItem,"TitleOfCourtesy")%>'/>
<asp:Button id="update" runat="server" Text="更新" CommandName="update" />
<asp:Button id="cancel" runat="server" Text="取消" CommandName="cancel" />
</EditItemTemplate>
</asp:DataList>
后台代码:
private void dlEditItem_CancelCommand(object source, System.Web.UI.WebControls.DataListCommandEventArgs e)
{
//设置DataList控件的编辑项的索引为-1,既取消编辑
dlEditItem.EditItemIndex=-1;
//数据绑定
DataListDataBind();
}
private void dlEditItem_EditCommand(object source, System.Web.UI.WebControls.DataListCommandEventArgs e)
{
//设置DataList控件的编辑项的索引为当前项
dlEditItem.EditItemIndex=e.Item.ItemIndex;
//数据绑定
DataListDataBind();
}
private void dlEditItem_UpdateCommand(object source, System.Web.UI.WebControls.DataListCommandEventArgs e)
{
//取得编辑行的关键字段的值
int empID=(int)dlEditItem.DataKeys[e.Item.ItemIndex];
//取得文本框中输入的内容
TextBox newTitle=(TextBox)e.Item.FindControl("Title");
TextBox newTitleOfCour=(TextBox)e.Item.FindControl("TitleOfCourtesy");
string sqlCom="update Employees set Title='"+newTitle.Text+"',TitleOfCourtesy='"+newTitleOfCour.Text+"' where EmployeeID="+empID.ToString();
//定义数据连接对象,其中数据库连接字符串是在Web.Config文件中定义的
SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["DataBaseCon"].ToString());
//定义命令对象
SqlCommand cmd=new SqlCommand(sqlCom,conn);
//打开数据连接
conn.Open();
try
{
//执行SQL命令
cmd.ExecuteNonQuery();
//取消编辑
dlEditItem.EditItemIndex=-1;
DataListDataBind();
}
catch(Exception err)
{
//输入异常信息
Response.Write(err.ToString());
}
finally
{
//关闭连接对象
conn.Close();
}
}
private void DataListDataBind()
{
SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["DataBaseCon"].ToString());
SqlDataAdapter da=new SqlDataAdapter("select * from Employees",conn);
DataSet ds=new DataSet();
try
{
da.Fill(ds,"testTable");
dlEditItem.DataSource=ds.Tables["testTable"];
dlEditItem.DataBind();
}
catch(Exception error)
{
Response.Write(error.ToString());
}
}