ASP.NET—006:GridView删除一行JS实现

原文作者:杨友山

原文地址http://blog.csdn.net/yysyangyangyangshan/article/details/22321921

前一篇说了JS增加一行,那么如何删除一行呢?
也很简单,还是用JS实现,JS获取要删除的一行,并得到这一行数据的ID(绑定数据时将ID放在一个隐藏空间中)。然后使用ajax方法传到后台,完成真正的删除。同时在前台也删掉gridview中的一行。
效果如下
确认删除

删除成功

代码如下:
前台代码,主要看DelItem这个JS方法

<!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 id="Head1" runat="server">
    <title></title>
</head>
<body id="Body1" runat="server">
     <form id="Form1" runat="server">
      <asp:Button ID="btnAdd" runat="server" OnClientClick="return AddNewRow();return false;" Text="增加"/>
      
      <asp:GridView ID="dgPersons" runat="server" EnableViewState="false" CellPadding="4"
       GridLines="Horizontal" PageChange="TextBox" AutoGenerateColumns="False" SortMode="Total" ForeColor="#333333"
       CellSpacing="1" Width="60%" ShowNoRecordTip="True">
     <Columns>


       <asp:TemplateField>
       <ItemTemplate>
         <%#Container.DataItemIndex +1%>
         <input id="hideID" type="hidden" runat="server" value=‘<%#Eval("p_id")%>‘ />
       </ItemTemplate>
       <HeaderTemplate>
           <span>序号</span>
       </HeaderTemplate>
       </asp:TemplateField>


       <asp:TemplateField>
       <ItemTemplate>
        <span> <%#Eval("p_name")%></span>
       </ItemTemplate>
       <HeaderTemplate>
           <span>姓名</span>
       </HeaderTemplate>
       </asp:TemplateField>


        <asp:TemplateField>
       <ItemTemplate>
        <span> <%#Eval("p_age")%></span>
       </ItemTemplate>
       <HeaderTemplate>
           <span>年龄</span>
       </HeaderTemplate>
       </asp:TemplateField>
      
       <asp:TemplateField>
       <ItemTemplate>
        <span> <%#Eval("p_sex")%></span>
       </ItemTemplate>
       <HeaderTemplate>
           <span>性别</span>
       </HeaderTemplate>
       </asp:TemplateField>


             
       <asp:TemplateField>
       <ItemTemplate>
         <a href ="JavaScript:viod(0)" onclick="javascript:DelItem(this)">删除</a>
       </ItemTemplate>
       <HeaderTemplate>
           <span>操作</span>
       </HeaderTemplate>
       </asp:TemplateField>


     </Columns>
     <FooterStyle BackColor="#5D7B9D" Font-Bold="True" HorizontalAlign="Center" ForeColor="White" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <RowStyle HorizontalAlign="Center" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <EditRowStyle BackColor="#999999" />
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
    </asp:GridView>
    </form>
</body>
<script type="text/javascript" src="/Scripts/Ajax.js"></script>
<script type="text/javascript" src="/Scripts/jquery-1.4.1.js"></script>


<script language="javascript" type="text/javascript">
    var dgPersonsID = "<%= dgPersons.ClientID %>";
    $(document).ready(function () {
        $("#dgPersons tr").eq(1).hide();
    });


    function AddNewRow() {
        var tr = $("#dgPersons tr").eq(1).clone();
        tr.show();
        tr.appendTo("#dgPersons");
        refreshNo();
        return false;
    }


    function DelItem(obj) {
        var elm = event.target || event.srcElement;
        if (elm.disabled) {
            return false;
        }
        if (confirm("真的要删除?")) {
            var row = obj.parentElement.parentElement;
            var deleteData = new Object();
            deleteData.ID = row.cells[0].children[0].value;
            var postData = deleteData;
            postData.operateType = "Delete";
            var htmlobj = $.ajax({
                type: "POST",
                data: postData,
                async: true,
                success: function (result) {
                    var tr = elm.parentNode.parentNode;
                    tr.parentNode.removeChild(tr);
                    alert("删除成功!")
                },
                error: function (result) {
                    alert("删除失败!");
                }
            });
        }
        refreshNo();


        return false;
    }


    function refreshNo() {


        var dgg = document.getElementById(dgPersonsID);
        var index = 1;
        for (var i = 2; i < dgg.rows.length; ++i) {
            var cells = dgg.rows[i].cells;
            var row = dgg.rows[i];
            if (row.style.display != "none") {
                cells[0].firstChild.nodeValue = index++;
            }
        }


        return false;
    }
</script>
后台代码
获取到传来的数据id删除,然后回应前台就可以了
 public partial class ChildFrm : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            switch (Request["operateType"])
            {
                case "Delete":


                    DeleteSingleData();


                    return;


                default:


                    break;
            }


            if (!IsPostBack)
            {
               DataTable dt= InitData();


               this.dgPersons.DataSource = dt;


               this.dgPersons.DataBind();
            }
        }


        private DataTable InitData()
        {
            DataTable PersonCollect = new DataTable();


            PersonCollect = new DataTable();


            PersonCollect.Columns.Add("p_id");


            PersonCollect.Columns.Add("p_name");


            PersonCollect.Columns.Add("p_age");


            PersonCollect.Columns.Add("p_sex");


            if (PersonCollect.Rows.Count < 1)
            {
                for (int i = 0; i < 1; i++)
                {
                    DataRow nrow = PersonCollect.NewRow();


                    nrow["p_id"] = System.Guid.NewGuid().ToString();


                    nrow["p_name"] = "西北白杨树";


                    nrow["p_age"] = 27;


                    nrow["p_sex"] = "男";


                    PersonCollect.Rows.Add(nrow);
                }
            }


            return PersonCollect;
        }


        protected void DeleteSingleData()
        {
            string id = Request["ID"].ToString();


            //用ID自己写代码删除数据库


            SendTextMessage("success");
        }


        protected void SendTextMessage(string message)
        {
            Response.ContentType = "text/plain";


            Response.Write(message);


            Response.End();
        }
    }
 代码下载http://download.csdn.net/detail/yysyangyangyangshan/7109385

ASP.NET—006:GridView删除一行JS实现,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。