[转]GridView中直接新增行、编辑和删除

本文转自:http://www.cnblogs.com/gdjlc/archive/2009/11/10/2086951.html

.aspx 





<div><asp:Button runat="server" ID="btnAdd" Text="新增" OnClick="btnAdd_Click" /></div>  
 <asp:GridView ID="gv" runat="server" AllowPaging="True" AllowSorting="True" DataKeyNames="id"  
     AutoGenerateColumns="False" OnRowCancelingEdit="gv_RowCancelingEdit" OnRowEditing="gv_RowEditing"  
     OnRowUpdating="gv_RowUpdating" OnRowDeleting="gv_RowDeleting" OnRowDataBound="gv_RowDataBound">  
     <Columns>  
         <asp:TemplateField HeaderText="名称">  
             <EditItemTemplate>  
                 <asp:TextBox ID="txtName" runat="server" Text='<%# Bind("txtName") %>'></asp:TextBox>  
                 <asp:RequiredFieldValidator runat="server" ID="rfvtxtName" ControlToValidate="txtName"  
                     Display="Dynamic" ErrorMessage="*不能为空" ForeColor="Red"></asp:RequiredFieldValidator>  
             </EditItemTemplate>  
             <ItemTemplate>  
                 <asp:Label ID="lblName" runat="server" Text='<%# Bind("txtName") %>'></asp:Label>  
             </ItemTemplate>  
             <ItemStyle HorizontalAlign="Center" />  
         </asp:TemplateField>  
         <asp:TemplateField HeaderText="状态">  
             <EditItemTemplate>  
                 <asp:DropDownList ID="ddlIsEnable" runat="server">  
                     <asp:ListItem Value="True">启用</asp:ListItem>  
                     <asp:ListItem Value="False">停用</asp:ListItem>  
                 </asp:DropDownList>  
                 <asp:HiddenField ID="hfIsEnable" runat="server" Value='<%# Eval("IsEnable")%>' />  
             </EditItemTemplate>  
             <ItemTemplate>  
                 <asp:Label ID="lblIsEnable" runat="server" Text='<%# Eval("IsEnable").ToString() == "True" ? "启用" : "停用" %>'></asp:Label>  
             </ItemTemplate>  
             <ItemStyle HorizontalAlign="Center" />  
         </asp:TemplateField>  
         <asp:TemplateField HeaderText="排序号">  
             <EditItemTemplate>  
                 <asp:TextBox ID="txtOrder" runat="server" Text='<%# Bind("Order") %>'></asp:TextBox>  
                 <asp:RegularExpressionValidator runat="server" ID="revOrder" ControlToValidate="txtOrder"  
                     ValidationExpression="\d+" Display="Dynamic" ErrorMessage="*必须为整数"></asp:RegularExpressionValidator>  
             </EditItemTemplate>  
             <ItemTemplate>  
                 <asp:Label ID="lblOrder" runat="server" Text='<%# Eval("Order") %>'></asp:Label>  
             </ItemTemplate>  
             <ItemStyle HorizontalAlign="Center" />  
         </asp:TemplateField>  
         <asp:CommandField ShowDeleteButton="true" ShowEditButton="true" EditText="编辑" DeleteText="删除"  
             CancelText="取消" HeaderText="操作" />  
     </Columns>  
     <EmptyDataTemplate>  
         没有您查询的数据  
     </EmptyDataTemplate>  
     <PagerSettings Visible="false" />  
 </asp:GridView>  


.aspx.cs 





public partial class CategoryList : System.Web.UI.Page  
{  
    private static List<Category> cateList;  
    private ICategory iCate = IOC.R<ICategory>();  
    protected void Page_Load(object sender, EventArgs e)  
    {  
        if (!IsPostBack)  
        {  
            BindGV(true);  
        }  
    }  
    private void BindGV(bool refresh)  
    {  
        if (refresh || cateList == null)  
        {  
            cateList = iCate.List();  
        }  
        this.gv.DataSource = cateList;  
        this.gv.DataBind();  
    }  
    protected void gv_RowEditing(object sender, GridViewEditEventArgs e)  
    {  
        gv.EditIndex = e.NewEditIndex;  
        BindGV(false);  
        HiddenField hfIsEnable = (HiddenField)gv.Rows[e.NewEditIndex].FindControl("hfIsEnable");  
        DropDownList ddlIsEnable = (DropDownList)gv.Rows[e.NewEditIndex].FindControl("ddlIsEnable");  
        ddlIsEnable.SelectedValue = hfIsEnable.Value;  
    }  
    protected void gv_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)  
    {  
        gv.EditIndex = -1;  
        BindGV(false);  
    }  
    //更新  
    protected void gv_RowUpdating(object sender, GridViewUpdateEventArgs e)  
    {  
        long id = Convert.ToInt32(gv.DataKeys[e.RowIndex].Values[0].ToString());  
        string name = ((TextBox)gv.Rows[e.RowIndex].FindControl("txtName")).Text.Trim();  
        bool isEnable = Convert.ToBoolean(((DropDownList)gv.Rows[e.RowIndex].FindControl  
lIsEnable")).SelectedValue);  
        string txtOrder = ((TextBox)gv.Rows[e.RowIndex].FindControl("txtOrder")).Text;  
        int order = string.IsNullOrEmpty(txtOrder) ? 0 : Convert.ToInt32(txtOrder);  
                     
        long newId = id;              
        Category category = iCate.Get(id);  
        if (category != null)//如果数据库已存在该条记录,则更新  
        {  
            iCate.Update(id, c =>  
            {  
                c.Name = name;  
                c.IsEnable = isEnable;  
                c.Order = order;  
            });  
        }  
        else//新增   
        {  
            Category cNew = new Category  
            {  
                Name = name,  
                IsEnable = isEnable,  
                Order = order  
            };  
            iCate.Insert(cNew);  
            newId = cNew.ID;  
        }  
        Category cate = cateList.Where(c => c.ID == id).ToList().SingleOrDefault();  
        if (cate != null)  
        {  
            cate.ID = newId;  
            cate.Name = name;  
            cate.IsEnable = isEnable;  
            cate.Order = order;  
        }  
          
        gv.EditIndex = -1;  
        BindGV(false);  
    }  
    //删除  
    protected void gv_RowDeleting(object sender, GridViewDeleteEventArgs e)  
    {  
        long id = Convert.ToInt64(gv.DataKeys[e.RowIndex].Values[0].ToString());  
        Category cate = cateList.Where(c => c.ID == id).ToList().SingleOrDefault();  
        if (cate != null)  
        {  
            cateList.Remove(cate);  
        }  
        iCate.Delete(id);  
        this.BindGV(false);  
    }  
    //新增一行记录  
    protected void btnAdd_Click(object sender, EventArgs e)  
    {  
        long maxId = cateList.Max(c => c.ID) + 1;  
        Category cate = new Category()  
        {  
            ID = maxId,  
            Name = "",  
            Order = 0,  
            IsEnable = true  
        };  
        cateList.Add(cate);  
        this.gv.EditIndex = cateList.Count - 1;  
        this.BindGV(false);  
    }  
    protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)  
    {               
        if (e.Row.RowType == DataControlRowType.DataRow)  
        {  
            LinkButton btn = ((LinkButton)e.Row.Cells[3].Controls[2]);  
            if (btn.Text == "删除")  
            {  
                btn.Attributes.Add("onclick", "javascript:return confirm('您确信要删除吗!?')");  
            }  
        }         
    }  
}  

 

posted on 2016-01-15 12:23  freeliver54  阅读(1050)  评论(0编辑  收藏  举报

导航