触摸屏租赁
Touch screen rental
广告机租赁
Advertising rental
机器人租赁
Robot leasing
 当前位置:首页 > > asp.net 中datalist 加删除功能

前台

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>无标题页</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="添加" />
        <asp:Button ID="Button2" runat="server" Text="返回上级" />
<table border="1">
          <tr>
            <th>地名</th>
            <th>邮编</th>
            <th>管理</th>
            <th>删除</th>
          </tr>
          <asp:DataList ID="DataList1" runat="server" DataKeyField="id"                 ondeletecommand="DataList1_DeleteCommand">
          <ItemTemplate>
          <td><%#Eval("name") %></td>
          <td><%#Eval("postcode") %></td>
          <td>
              <asp:HyperLink ID="HyperLink1" NavigateUrl='<%# Eval("id", "Default.aspx?id={0}") %>' Text="下级地区" runat="server"></asp:HyperLink></td>
          <td>
<asp:LinkButton ID="LinkButton1" OnClientClick="return window.confirm('您真的要删除此记录吗?');" CommandName="delete" Text="删除"
                  runat="server" ></asp:LinkButton> </td>
          </ItemTemplate>
          </asp:DataList>
    </table>      
    </div>
    </form>
</body>
</html>

 

后台

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    private void bind() {
        SqlConnection con = new SqlConnection("Server=.;uid=sa;pwd=1;database=member");
        con.Open();
        string sql = ("select * from members");
        SqlCommand cmd = new SqlCommand(sql, con);
        SqlDataReader sdr = cmd.ExecuteReader();
        DataList1.DataSource = sdr;
        DataList1.DataBind();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
   
        if (!IsPostBack)
        {
            bind();
        }

    }

    protected void DataList1_DeleteCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName == "delete")
        {
            int id = Convert.ToInt32(DataList1.DataKeys[e.Item.ItemIndex]);
            SqlConnection con = new SqlConnection("Server=.;uid=sa;pwd=1;database=member");
            con.Open();
            string sql = string.Format("delete from members where id='{0}'",id);
            SqlCommand cmd = new SqlCommand(sql,con);                     
            cmd.ExecuteNonQuery();
            bind();
        }
    }
}


工作室地址:重庆石桥铺电脑城B座 | 微信:z35544216 | 网址:www.35544216.com