控件設定:
<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: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;
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()
SqlDataAdapter da=new SqlDataAdapter("select * from Employees",conn);
DataSet ds=new DataSet();
da.Fill(ds,"testTable");
dlEditItem.DataSource=ds.Tables["testTable"];
dlEditItem.DataBind();
catch(Exception error)
Response.Write(error.ToString());