ASP.NET中利用Repeater實現增刪改操作

暖楓無敵發表於2012-02-21

有這樣一個需求,就是頁面上一個"新增"按鈕,點選後在Repeater內動態生成一行,使用者填寫後儲存並顯示在Repeater中。

在Repeater內部的每項都有一個編輯和刪除功能,點選“編輯”後,出現“更新”和“取消”按鈕。

這其中當然也包括了在Repeater內包含下拉框DropDownList控制元件,也是方便了解是如何繫結和選中資料庫中的預設值。

一切盡在如下程式碼,裡面使用的DM是一個資料庫訪問類,可以根據自己需要修改,使用SQLHelper等之類都可以的。


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DynamicRepeater.aspx.cs"
    Inherits="WebApplication1.DynamicRepeater" %>

<!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="btnNew" runat="server" Text="新建" OnClick="btnNew_OnClick" />
        <asp:Repeater ID="rpCustomerInfo" runat="server" OnItemDataBound="rpCustomerInfo_ItemDataBound" OnItemCommand="rpCustomerInfo_ItemCommand">
            <HeaderTemplate>
                <table>
                    <tr>
                        <th>
                            ID
                        </th>
                        <th>
                            型別
                        </th>
                        <th>
                            名稱
                        </th>
                        <th>
                            編輯
                        </th>
                    </tr>
                    <asp:Panel ID="plNew" runat="server" Visible="false">
                    <tr>
                        <td>
                            <asp:Label ID="Label2" runat="server" Text='<%#Eval("ID") %>'></asp:Label>
                        </td>
                        <td>
                            <asp:DropDownList ID="ddlType2" runat="server">
                            </asp:DropDownList>
                        </td>
                        <td>
                            <asp:TextBox ID="TextBox2" runat="server" Text='<%#Eval("Name")%>'></asp:TextBox>
                        </td>
                        <td>
                            <asp:LinkButton runat="server" ID="lbtSave" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "ID")%>'
                                CommandName="Save" Text="儲存"></asp:LinkButton>   
                            <asp:LinkButton runat="server" ID="lbtCancel2" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "ID")%>'
                                CommandName="Cancel2" Text="取消"></asp:LinkButton>
                        </td>
                    </tr>
                </asp:Panel>
            </HeaderTemplate>
            <ItemTemplate>
                <asp:Panel ID="PlItem" runat="server">
                    <tr>
                        <td>
                            <asp:Label ID="Label3" runat="server" Text='<%#Eval("ID") %>'></asp:Label>
                        </td>
                        <td>
                            <asp:Label ID="Label4" runat="server" Text='<%#Eval("Type") %>'></asp:Label>
                        </td>
                        <td>
                            <asp:Label ID="Label5" runat="server" Text='<%#Eval("Name") %>'></asp:Label>
                        </td>
                        <td>
                            <asp:LinkButton runat="server" ID="lbtEdit" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "ID")%>'
                                Text="編輯" CommandName="Edit"></asp:LinkButton>   
                            <asp:LinkButton runat="server" ID="lbtDelete" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "ID")%>'
                                Text="刪除" CommandName="Delete"></asp:LinkButton>
                        </td>
                    </tr>
                </asp:Panel>
                <asp:Panel ID="plEdit" runat="server">
                    <tr>
                        <td>
                            <asp:Label ID="Label1" runat="server" Text='<%#Eval("ID") %>'></asp:Label>
                        </td>
                        <td>
                            <asp:DropDownList ID="ddlType" runat="server">
                            </asp:DropDownList>
                        </td>
                        <td>
                            <asp:TextBox ID="TextBox1" runat="server" Text='<%#Eval("Name")%>'></asp:TextBox>
                        </td>
                        <td>
                            <asp:LinkButton runat="server" ID="lbtUpdate" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "ID")%>'
                                CommandName="Update" Text="更新"></asp:LinkButton>   
                            <asp:LinkButton runat="server" ID="lbtCancel" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "ID")%>'
                                CommandName="Cancel" Text="取消"></asp:LinkButton>
                        </td>
                    </tr>
                </asp:Panel>
            </ItemTemplate>
            <FooterTemplate>
                </table>
            </FooterTemplate>
        </asp:Repeater>
    </div>
    </form>
</body>
</html>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using USTC;

namespace WebApplication1
{
    public partial class DynamicRepeater : System.Web.UI.Page
    {
        DM dm = new DM();
        public int m_iID = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DataBinds();
            }
        }

        public void DataBinds()
        {
            string strSQL = "select * from SubTable where MainTableID=1";
            DataTable dt = dm.getsql(strSQL).Tables[0];
            this.rpCustomerInfo.DataSource = dt;
            this.rpCustomerInfo.DataBind();
        }

        protected void btnNew_OnClick(object sender, EventArgs e)
        {
            ((Panel)rpCustomerInfo.Controls[0].FindControl("PlNew")).Visible = true ;
        }


        protected void rpCustomerInfo_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            try
            {
                if (e.Item.ItemType == ListItemType.Header)
                {
                    DropDownList ddl2 = e.Item.FindControl("ddlType2") as DropDownList;
                    string strSQL2 = "select * from DataType";
                    ddl2.DataSource = dm.getsql(strSQL2);
                    ddl2.DataTextField = "Name";
                    ddl2.DataValueField = "ID";
                    ddl2.DataBind();
                    ddl2.Items.Insert(0, "--請選擇--");
                }
                if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
                {
                    DropDownList ddl = e.Item.FindControl("ddlType") as DropDownList;
                    string strSQL = "select * from DataType";
                    ddl.DataSource = dm.getsql(strSQL);
                    ddl.DataTextField = "Name";
                    ddl.DataValueField = "ID";
                    ddl.DataBind();
                    //設定選中值
                    DataRowView drv = (DataRowView)e.Item.DataItem;
                    ddl.Items.FindByValue(drv["Type"].ToString()).Selected = true;

                    string userid = drv["ID"].ToString();

                    if (userid != m_iID.ToString())
                    {
                        ((Panel)e.Item.FindControl("plItem")).Visible = true;
                        ((Panel)e.Item.FindControl("plEdit")).Visible = false;
                    }
                    else
                    {
                        ((Panel)e.Item.FindControl("plItem")).Visible = false;
                        ((Panel)e.Item.FindControl("plEdit")).Visible = true;
                    }
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
                ((Panel)e.Item.FindControl("plEdit")).Visible = false;
            }
        }

        protected void rpCustomerInfo_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "Save")
            {
                int v1 = int.Parse((e.Item.FindControl("ddlType2") as DropDownList).SelectedItem.Value);
                string v2 = (e.Item.FindControl("TextBox2") as TextBox).Text;
                //儲存
                string strSQL = "insert into SubTable values(1,"+v1+",'"+v2+"')";
                dm.execsql(strSQL);
            }
            else if (e.CommandName == "SaveCancel")
            {
                (e.Item.FindControl("PlNew") as Panel).Visible = false;
            }
            else if (e.CommandName == "Edit")
            {
                m_iID = int.Parse(e.CommandArgument.ToString());
            }
            else if (e.CommandName == "Cancel")
            {
                m_iID = -1;
            }
            else if (e.CommandName == "Update")
            {
                //更新
                int type = int.Parse((this.rpCustomerInfo.Items[e.Item.ItemIndex].FindControl("ddlType") as DropDownList).SelectedItem.Value);
                string name = (this.rpCustomerInfo.Items[e.Item.ItemIndex].FindControl("TextBox1") as TextBox).Text;
                string strSQL = "update SubTable  set Type="+type+",Name='"+name+"' where ID="+int.Parse(e.CommandArgument.ToString());
                dm.execsql(strSQL);
                this.Page.ClientScript.RegisterStartupScript(this.Page.GetType(), "key", "alert('更新ID:" + e.CommandArgument + "');", true);
            }
            else if (e.CommandName == "Delete")
            {
                //刪除
                string strSQL = "delete from SubTable where ID=" + int.Parse(e.CommandArgument.ToString());
                dm.execsql(strSQL);
                this.Page.ClientScript.RegisterStartupScript(this.Page.GetType(), "key", "alert('刪除ID:" + e.CommandArgument + "');", true);
            }
            DataBinds();

        }
    }
}

這樣一個簡單的Repeater內的增刪改查就實現了。


相關文章