前台代码:
前台代码
1 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
2 OnRowDeleting="GridView1_RowDeleting" onrowcommand="GridView1_RowCommand"
3 onrowdatabound="GridView1_RowDataBound">
4 <Columns>
5 <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" />
6 <asp:BoundField DataField="CompanyName" HeaderText="CompanyName" />
7 <asp:BoundField DataField="ContactName" HeaderText="ContactName" />
8 <asp:BoundField DataField="ContactTitle" HeaderText="ContactTitle" />
9 <asp:TemplateField HeaderText="删除">
10 <ItemTemplate>
11 <asp:Button ID="Button1" runat="server" Text="删除" CommandName="Delete" />
12 </ItemTemplate>
13 </asp:TemplateField>
14 <asp:TemplateField HeaderText="删除">
15 <ItemTemplate>
16 <asp:LinkButton OnClientClick="return confirm('确认删除吗?')" ID="LinkButton1" CommandArgument="<%#GridView1.Rows.Count %>" style="text-decoration:none" CommandName="DelResort" runat="server">删除</asp:LinkButton>
17 </ItemTemplate>
18 </asp:TemplateField>
19 </Columns>
20 </asp:GridView>
后台代码:
后台代码
1 protected void Page_Load(object sender, EventArgs e)
2 {
3
4 if (!IsPostBack)
5 {
6 databind();
7 }
8 }
9 public void databind()
10 {
11 SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Conn"].ToString());
12 SqlCommand cmd = new SqlCommand("SELECT * FROM CUSTOMERS", con);
13 SqlDataAdapter da = new SqlDataAdapter(cmd);
14 DataSet ds = new DataSet();
15 da.Fill(ds);
16 this.GridView1.DataSource = ds.Tables[0];
17 this.GridView1.DataKeyNames = new string[] { "CustomerID", "City" };
18 this.GridView1.DataBind();
19 }
20 protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
21 {
22 SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Conn"].ToString());
23 SqlCommand cmd = new SqlCommand("Delete From Customers where CustomerID=@CustomerID", con);
24 SqlParameter sp = new SqlParameter("@CustomerID", SqlDbType.NChar, 5);
25 sp.Value = this.GridView1.DataKeys[e.RowIndex].Values[0];
26 cmd.Parameters.Add(sp);
27 if (con.State == ConnectionState.Closed)
28 {
29 con.Open();
30 }
31 cmd.ExecuteNonQuery();
32 databind();
33 }
34 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
35 {
36
37 }
38 protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
39 {
40 if (e.CommandName == "DelResort")
41 {
42 int intID = int.Parse(e.CommandArgument.ToString());
43 string strKey = this.GridView1.DataKeys[intID].Values[0].ToString();
44 SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Conn"].ToString());
45 SqlCommand cmd = new SqlCommand("Delete From Customers where CustomerID=@CustomerID", con);
46 SqlParameter sp = new SqlParameter("@CustomerID", SqlDbType.NChar, 5);
47 sp.Value = strKey;
48 cmd.Parameters.Add(sp);
49 if (con.State == ConnectionState.Closed)
50 {
51 con.Open();
52 }
53 cmd.ExecuteNonQuery();
54 databind();
55 }
56 }