1. 程式人生 > >GridView行編輯、更新、取消、刪除事件用法

GridView行編輯、更新、取消、刪除事件用法

 

注意:當啟用編輯按鈕時,點選編輯按鈕後會使一整行都切換成文字框。為了是一行中的一部分是文字框,需要把以整行的所有列都轉換成模板,然後刪掉編輯模板中的程式碼。這樣就能使你想編輯的列轉換成文字框。

1.介面

<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"
            GridLines="None" AutoGenerateColumns="False"  DataKeyNames="ProductID"
            onrowdatabound="GridView1_RowDataBound" AllowPaging="True"
            onpageindexchanging="GridView1_PageIndexChanging"
            onrowcommand="GridView1_RowCommand"
            onrowcancelingedit="GridView1_RowCancelingEdit"
            onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating"
            onrowdeleting="GridView1_RowDeleting">
            <PagerSettings FirstPageText="首頁" LastPageText="尾頁"
                Mode="NextPreviousFirstLast" NextPageText="下一頁" PreviousPageText="上一頁" />
            <RowStyle BackColor="#E3EAEB" />
            <Columns>
                <asp:TemplateField HeaderText="ProductID">
 
                    <ItemTemplate>
                        <asp:Label ID="Label2" runat="server" Text='<%# Bind("ProductID") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="ProductName">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtName" runat="server" Text='<%# Bind("ProductName") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("ProductName") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="UnitPrice">
                    <ItemTemplate>
                        <asp:Label ID="Label3" runat="server" Text='<%# Bind("UnitPrice") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="操">

                    <ItemTemplate>
                        <asp:LinkButton ID="del" runat="server" OnClientClick="return confirm('您確定要刪除嗎?')" CommandName="dell" >刪除</asp:LinkButton>
                      
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:CommandField ShowEditButton="True" HeaderText="作">
               
                    <HeaderStyle  HorizontalAlign="Center" />
                        <ItemStyle  HorizontalAlign="Center"  Width="85px" ForeColor="Blue" />
                    </asp:CommandField>
            </Columns>
            <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White"
                HorizontalAlign="Right" />
            <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
            <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
            <EditRowStyle BackColor="#7C6F57" />
            <AlternatingRowStyle BackColor="White" />
        </asp:GridView>

2.前臺操控呼叫業務

DalBll db = new DalBll();
    static List<Products> tmpList = new List<Products>();
    protected void Page_Load(object sender, EventArgs e)
    {
       
        if(!IsPostBack)
        {
            InitGridView();
        }
    }

    private void InitGridView()
    {
        tmpList = db.GetDataList();
        this.GridView1.DataSource = tmpList;
        this.GridView1.DataBind();
    }

    //繫結資料時觸發
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Products tmp = e.Row.DataItem as Products;
            LinkButton lbtn = e.Row.FindControl("del") as LinkButton;
            if (lbtn != null && tmp != null)
                lbtn.CommandArgument = tmp.ProductID.ToString();//繫結主鍵
        }
    }

    //刪除資料
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "dell")
        {
            int productID = Convert.ToInt32(e.CommandArgument);
            db.Del(productID);
        }

    }

    //分頁
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        this.GridView1.PageIndex = e.NewPageIndex;
        InitGridView();
    }

    //切換到編輯模式
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        this.GridView1.EditIndex = e.NewEditIndex;
        InitGridView();
    }

    //取消
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        this.GridView1.EditIndex = -1;
        InitGridView();
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        //獲取當前頁索引
        int i = this.GridView1.EditIndex;
        //獲取文字框的值
        string productsName = ((TextBox)(this.GridView1.Rows[i].FindControl("txtName"))).Text.ToString();
        DataKey key = this.GridView1.DataKeys[e.RowIndex];
        int id = Convert.ToInt32(key[0].ToString());
        //首先找到該物件
        Products tmp = tmpList.Where(c => c.ProductID == id).First();
        tmp.ProductName = productsName;
        db.Update(tmp);
        InitGridView();
    }


3.各操作資料的程式碼

public class DalBll
    {
        NorthwindEntities db = new NorthwindEntities();

        public List<Products> GetDataList()
        {
            return db.Products.ToList();
        }

        public void Del(int productID)
        {
            Products tmp = db.Products.Where(c=>c.ProductID==productID).First();
            db.DeleteObject(tmp);
            db.SaveChanges();
        }

        public void Update(Products tmp)
        {
            //為引數物件建立實體鍵
            EntityKey key;
            object originalProductObj;
            //因引數物件不屬於上下文,因此為該引數物件建立上下文實體鍵
            key = db.CreateEntityKey("Products", tmp);
            db.TryGetObjectByKey(key, out originalProductObj);
            db.ApplyPropertyChanges(key.EntitySetName, tmp);
            db.SaveChanges();
           
        }