<form id="form1" runat="server">
<div>
<asp:DataList ID="DataList1" runat="server" Width="271px" OnItemCommand="DataList1_ItemCommand" OnEditCommand="DataList1_EditCommand" OnCancelCommand="DataList1_CancelCommand" OnUpdateCommand="DataList1_UpdateCommand" >
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="select">详细信息</asp:LinkButton>
<asp:LinkButton ID="LinkButton4" runat="server" CommandName="edit">编辑</asp:LinkButton>
<%#Eval("LastName") %><%#Eval("FirstName") %>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="LinkButton2" runat="server" CommandName="update">保存</asp:LinkButton>
<asp:LinkButton ID="LinkButton3" runat="server" CommandName="cancel">取消</asp:LinkButton>
<asp:TextBox ID="TextBox1" runat="server" Text=<%#Eval("City") %> Width="92px"></asp:TextBox>
</EditItemTemplate>
<HeaderTemplate>
页眉
<hr />
</HeaderTemplate>
<SeparatorTemplate>
<hr />
</SeparatorTemplate>
<SelectedItemTemplate>
<%#Eval("LastName") %>
<%#Eval("FirstName") %>
<%#Eval("City") %>
<%#Eval("Address") %>
</SelectedItemTemplate>
<FooterTemplate>
<hr />
页脚
</FooterTemplate>
</asp:DataList></div>
</form>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
databind();
}
}
private void databind()
{
//int curPage = Convert.ToInt32(Label1.Text);
SqlConnection con = new SqlConnection("server=.;uid=sa;pwd=;database=Northwind");
SqlDataAdapter sda = new SqlDataAdapter("select * from employees", con);
DataSet ds = new DataSet();
sda.Fill(ds, "emp");
DataList1.DataKeyField = "EmployeeID";
DataList1.DataSource=ds.Tables["emp"];
DataList1.DataBind();
}
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "select")
{
DataList1.SelectedIndex = e.Item.ItemIndex;
databind();
}
}
protected void DataList1_EditCommand(object source, DataListCommandEventArgs e)
{
DataList1.EditItemIndex = e.Item.ItemIndex;
databind();
}
protected void DataList1_UpdateCommand(object source, DataListCommandEventArgs e)
{
string empId = DataList1.DataKeys[e.Item.ItemIndex].ToString();
string city1 = ((TextBox)e.Item.FindControl("TextBox1")).Text;
SqlConnection con = new SqlConnection("server=.;uid=sa;pwd=;database=Northwind");
SqlCommand cmd = new SqlCommand("update employees set city='"+city1+"' where employeeid='"+empId+"'",con);
con.Open();
cmd.ExecuteNonQuery();
DataList1.EditItemIndex = -1;
databind();
}
protected void DataList1_CancelCommand(object source, DataListCommandEventArgs e)
{
DataList1.EditItemIndex = -1;
databind();
}
CommandName(select update cancel delete)