.NET2.0在Repeater中实现删除

    技术2022-05-11  22

    虽然Repeater控件没有象GridView那样常用,但有一些特定的场合还是需要用到Repeater的,其实在Net2.0中,FormView控件也可以实现类似于Repeater的效果,而且都是通过模板(Template)来显示数据。

    然而,在Repeater控件对控件进行删除就没有GridView那样简单。下面示例如下:

    Default.aspx:

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Repeater_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:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"            SelectCommand="SELECT * FROM [Region]"></asp:SqlDataSource>        </div>        <asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1" OnItemCommand="Repeater1_ItemCommand" OnItemCreated="Repeater1_ItemCreated">                <ItemTemplate >        <table border="1">        <tr>        <td>        <asp:Label Text ='<%#Eval("regionid") %>' runat ="server" ID="Label1"></asp:Label>                <asp:Label Text='<%#Eval("regiondescription") %>' runat="server" ></asp:Label>        <asp:Button Text ="Delete" runat ="server"  ID="Button1"/>        </td>        </tr>        </table>        </ItemTemplate>        </asp:Repeater>    </form></body></html>

    Default.aspx.cs:

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

    public partial class Repeater_Default : System.Web.UI.Page{    protected void Page_Load(object sender, EventArgs e)    {

        }    protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)    {                switch (((Button)e.Item.FindControl ("Button1")).Text)        {            case "Delete":

                    SqlConnection conn = new SqlConnection("server=.;database=northwind;uid=sa;pwd=sa;");                conn.Open();                SqlCommand comm = new SqlCommand("delete from region where regionid='" + ((Label)e.Item.FindControl("Label1")).Text+"'",conn );                comm.ExecuteNonQuery();                conn.Close();

                    Response.Write(((Label)e.Item.FindControl ("Label1")).Text);                break;        }    }    protected void Repeater1_ItemCreated(object sender, RepeaterItemEventArgs e)    {        for (int i = 0; i < this.Repeater1.Items.Count; i++)        {            ((Button)this.Repeater1.Items[i].FindControl("Button1")).Attributes.Add("onclick", "alert('ff')");        }            }}

    这样就可以实现删除了。


    最新回复(0)