ListView在列表中新增一行的操作(增加、取消)

前台:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AddMeaSub2New.aspx.cs"
    Inherits="BQ.WebApp.DataEntry.AddMeaSub2New" MasterPageFile="~/Web.Master" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">

    <script language="javascript" type="text/javascript" src="/js/jquery-1.4.2.min.js"></script>

    <script language="javascript" type="text/javascript">
        $.fn.numeral = function() {
            $(this).css("ime-mode", "disabled");
            this.bind("keypress", function() {
                if (event.keyCode == 46) {
                    if (this.value.indexOf(".") != -1) {
                        return false;
                    }
                } else {
                    return event.keyCode >= 46 && event.keyCode <= 57;
                }
            });
            this.bind("blur", function() {
                if (this.value.lastIndexOf(".") == (this.value.length - 1)) {
                    this.value = this.value.substr(0, this.value.length - 1);
                } else if (isNaN(this.value)) {
                    this.value = "";
                }
            });
            //            this.bind("paste", function() {
            //                var s = clipboardData.getData('text');
            //                if (!/D/.test(s));
            //                value = s.replace(/^0*/, '');
            //                return false;
            //            });
            this.bind("dragenter", function() {
                return false;
            });
            //            this.bind("keyup", function() {
            //                if (/(^0+)/.test(this.value)) {
            //                    this.value = this.value.replace(/^0*/, '');
            //                }
            //            });
        };
    </script>

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <div class="righttop">
        <asp:ImageButton ID="btn_ReturnList" runat="server" ImageUrl="~/Images/b06.gif" OnClick="btn_ReturnList_Click" /></div>
    <asp:ListView ID="ListView1" DataKeyNames="ID" runat="server" OnItemUpdating="List_ItemUpdating"
        OnItemEditing="ListView1_ItemEditing" OnItemDataBound="ListView_ItemDataBound"
        OnItemCanceling="ListView_ItemCanceling" OnItemDeleting="ListView1_ItemDeleting"
        OnItemInserting="ListView1_ItemInserting">
        <LayoutTemplate>
            <table class="TableSub">
                <tr>
                    <th scope="col">
                        <asp:Label ID="LinkButton1" runat="server" Text="二次装修补偿项目" />
                    </th>
                    <th scope="col">
                        <asp:Label ID="LinkButton3" runat="server" Text="数量" />
                    </th>
                    <th scope="col">
                        <asp:Label ID="LinkButton2" runat="server" Text="单价" />
                    </th>
                    <th scope="col">
                        <asp:Label ID="Label1" runat="server" Text="金额" />
                    </th>
                    <th scope="col" id="update_Th" runat="server">
                        修改
                    </th>
                    <th scope="col" id="del_Th" runat="server">
                        删除
                    </th>
                </tr>
                <asp:PlaceHolder ID="itemPlaceholder" runat="server"></asp:PlaceHolder>
            </table>
        </LayoutTemplate>
        <ItemTemplate>
            <tr>
                <td>
                    <%#Eval("ITEM_NAME")%>
                </td>
                <td>
                    <%#Eval("ITEM_COUNT")%>
                </td>
                <td>
                    <%#Eval("UNIT_PRICE")%>
                </td>
                <td>
                    <font color="red">
                        <asp:Label ID="labPriceTotal" runat="server" Text='<%#Sub2Total(Eval("ID").ToString()) %>'></asp:Label></font>
                </td>
                <td id="update_Td" runat="server">
                    <asp:LinkButton ID="btn_Edit" runat="server" Text="修改" CommandName="Edit"></asp:LinkButton>
                </td>
                <td id="del_Td" runat="server">
                    <asp:LinkButton ID="LinkButton4" runat="server" Text="删除" CommandName="Delete" OnClientClick="return confirm('是否确认删除?');"></asp:LinkButton>
                </td>
            </tr>
        </ItemTemplate>
        <EditItemTemplate>
            <tr>
                <td align="center">
                    <asp:DropDownList runat="server" ID="ddl_item_name" />
                    <asp:HiddenField ID="hf_item_name" runat="server" Value='<%#Eval("ITEM_NAME")%>' />
                </td>
                <td align="center">
                    <asp:TextBox runat="server" ID="tb_item_count" Text='<%#Eval("ITEM_COUNT")%>'></asp:TextBox>
                </td>
                <td align="center">
                    <asp:Label runat="server" ID="tb_unit_price" Text='<%#Eval("UNIT_PRICE")%>'></asp:Label>
                    <asp:HiddenField ID="hf_price" runat="server" Value="0" />
                </td>
                <td>
                    <font color="red">
                        <asp:Label ID="labPriceTotal" runat="server" Text='<%#Sub2Total(Eval("ID").ToString()) %>'></asp:Label></font>
                </td>
                <td align="center">
                    <asp:Button ID="btn_Update" runat="server" CommandName="Update" Text="确认" CssClass="btn" />
                    &nbsp;
                    <asp:Button ID="btn_Cancel" runat="server" CommandName="Cancel" Text="取消" CausesValidation="false"
                        CssClass="btn" />
                </td>
                <td>
                    <asp:LinkButton ID="LinkButton4" runat="server" Text="删除" CommandName="Delete" OnClientClick="return confirm('是否确认删除?');"></asp:LinkButton>
                </td>
            </tr>
        </EditItemTemplate>
        <InsertItemTemplate>
            <tr>
                <td align="center">
                    <asp:DropDownList runat="server" ID="ddl_item_name" />
                    <asp:HiddenField ID="hf_item_name" runat="server" Value="请选择" />
                </td>
                <td align="center">
                    <asp:TextBox runat="server" ID="tb_item_count" Text="0"></asp:TextBox>
                </td>
                <td align="center">
                    <asp:Label runat="server" ID="tb_unit_price" Text="0"></asp:Label>
                    <asp:HiddenField ID="hf_price" runat="server" Value="0" />
                </td>
                <td>
                    <font color="red">
                        <asp:Label runat="server" ID="total" Text="0"></asp:Label></font>
                </td>
                <td align="center">
                    <asp:Button ID="btn_Update" runat="server" CommandName="Insert" Text="增加" CssClass="btn" />
                    &nbsp;
                    <asp:Button ID="btn_Cancel" runat="server" CommandName="Cancel" Text="取消" CausesValidation="false"
                        CssClass="btn" />
                </td>
                <td>
                </td>
            </tr>
        </InsertItemTemplate>
        <EmptyItemTemplate>
        </EmptyItemTemplate>
    </asp:ListView>
    <asp:Button ID="btnAddMea" runat="server" Text="新增" CssClass="btn" OnClick="btnAdd_Click" />
    <asp:Button ID="btnReport" runat="server" Text="生成报表" CssClass="btn" 
        onclick="btnReport_Click" />
    <p>
        <asp:Label ID="selectLab" runat="server"></asp:Label></p>
</asp:Content>

后台:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BQ.BLL.DataEntry;
using BQ.Utility;
using BQ.Entity;
using System.Web.UI.HtmlControls;

namespace BQ.WebApp.DataEntry
{
    public partial class AddMeaSub2New : System.Web.UI.Page
    {
        public long FamilyId
        {
            get
            {
                if (Request.IsHasRequestKey("familyid"))
                {
                    return Request.GetRequestQueryString<long>("familyid");
                }
                return 0;
            }
        }

        public TMeasureOper tmo
        {
            get
            {
                return new TMeasureOper(FamilyId);
            }
        }

        public string Sub2Total(string ID)
        {
            CalculationMeasure talMe = new CalculationMeasure();
            return talMe.CalculationMeasureSub2(Int64.Parse(ID)).ToString();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (FamilyId == 0)
                {
                    btnAddMea.Visible = false;
                    PageScript.MessageShow(Page, "参数错误,请选择具体拆迁户");
                    return;
                }

                BindData();
            }
        }

        private void BindData()
        {
            ListView1.DataSource = tmo.GetMeasureSub2EntityNew;
            ListView1.DataBind();
        }

        protected void List_ItemUpdating(object sender, ListViewUpdateEventArgs e)
        {
            long ID = Convert.ToInt64(ListView1.DataKeys[e.ItemIndex].Value.ToString());
            TextBox txtItemCount = (TextBox)ListView1.Items[e.ItemIndex].FindControl("tb_item_count");
            if (string.IsNullOrEmpty(txtItemCount.Text))
            {
                PageScript.MessageShow(Page, "数量不能为空");
                return;
            }
            HiddenField Price = (HiddenField)ListView1.Items[e.ItemIndex].FindControl("hf_price");
            DropDownList dropStructureCliId = (DropDownList)ListView1.Items[e.ItemIndex].FindControl("ddl_item_name");
            string itemName = dropStructureCliId.SelectedItem.Text;
            if (itemName == "请选择")
            {
                PageScript.MessageShow(Page, "请选择装修项目");
                return;
            }
            T_MEASURE_SUB2 sub2 = new T_MEASURE_SUB2();
            sub2.ID = ID;
            sub2.ITEM_COUNT = double.Parse(txtItemCount.Text);
            sub2.ITEM_NAME = itemName;
            sub2.UNIT_PRICE = double.Parse(Price.Value);
            sub2.NEW_DEGREE = 100;
            MeasureBLL bll = new MeasureBLL();
            bll.UpdateMeasureRecord(sub2);
            ListView1.EditIndex = -1;
            BindData();
        }

        protected void ListView1_ItemInserting(object sender, ListViewInsertEventArgs e)
        {
            ListViewItem item = e.Item;
            TextBox txtItemCount = (TextBox)item.FindControl("tb_item_count");
            if (string.IsNullOrEmpty(txtItemCount.Text))
            {
                PageScript.MessageShow(Page, "数量不能为空");
                return;
            }
            HiddenField Price = (HiddenField)item.FindControl("hf_price");
            DropDownList dropStructureCliId = (DropDownList)item.FindControl("ddl_item_name");
            string itemName = dropStructureCliId.SelectedItem.Text;
            if (itemName == "请选择")
            {
                PageScript.MessageShow(Page, "请选择装修项目");
                return;
            }
            T_MEASURE_SUB2 sub2 = new T_MEASURE_SUB2();
            sub2.ITEM_COUNT = double.Parse(txtItemCount.Text);
            sub2.ITEM_NAME = itemName;
            sub2.UNIT_PRICE = double.Parse(Price.Value);
            sub2.NEW_DEGREE = 100;
            sub2.FAMILY_ID = FamilyId;
            MeasureBLL bll = new MeasureBLL();
            bll.AddMeasureRecord(sub2);
            ListView1.InsertItemPosition = InsertItemPosition.None;
            BindData();
        }

        protected void ListView_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            if (e.Item.ItemType == ListViewItemType.DataItem)
            {
                ItemData(e.Item);
            }

            if (SystemUserBusiness.GetUserRoleName == "领导")
            {

                ListView1.FindControl("del_Th").Visible = false;
                if (e.Item.ItemType == ListViewItemType.DataItem)
                {
                    HtmlTableCell delTd = (HtmlTableCell)e.Item.FindControl("del_Td");
                    if (delTd != null)
                    {
                        delTd.Visible = false;
                    }
                }

                ListView1.FindControl("update_Th").Visible = false;
                if (e.Item.ItemType == ListViewItemType.DataItem)
                {
                    HtmlTableCell updateTd = (HtmlTableCell)e.Item.FindControl("update_Td");
                    if (updateTd != null)
                    {
                        updateTd.Visible = false;
                    }
                }
                btnAddMea.Visible = false;
            }

        }

        /// <summary>
        /// 绑定选定的行的值
        /// </summary>
        /// <param name="item"></param>
        private void ItemData(ListViewItem item)
        {
            if ((item.FindControl("ddl_item_name")) != null)
            {
                string itemName = ((HiddenField)item.FindControl("hf_item_name")).Value.Trim();
                DropDownList dropStructureCliId = (DropDownList)item.FindControl("ddl_item_name");
                tmo.FillDownList(dropStructureCliId, "装修");
                dropStructureCliId.SelectedIndex = dropStructureCliId.Items.IndexOf(dropStructureCliId.Items.FindByText(itemName));
                Label txtUnitPriceCliId = (Label)item.FindControl("tb_unit_price");
                TextBox txtItemCount = (TextBox)item.FindControl("tb_item_count");
                HiddenField hfprice = (HiddenField) item.FindControl("hf_price");
                hfprice.Value = txtUnitPriceCliId.Text;
                string WriteScript = ""; 
                WriteScript += string.Format("<script>");
                WriteScript += string.Format("$("#{0}").numeral();", txtItemCount.ClientID);
                WriteScript += " $("#" + dropStructureCliId.ClientID.ToString() + "").bind("click", function(event) { ";
                WriteScript += string.Format(" var sleValue = $('#{0} option:selected').val();", dropStructureCliId.ClientID.ToString());
                WriteScript += string.Format("$("#{0}").text(sleValue);", txtUnitPriceCliId.ClientID);
                WriteScript += string.Format("$("#{0}").val(sleValue);", hfprice.ClientID);
                WriteScript += " });";
                WriteScript += string.Format("</script>");
                selectLab.Text = WriteScript;
            }
        }

        protected void ListView1_ItemEditing(object sender, ListViewEditEventArgs e)
        {
            ListView1.InsertItemPosition = InsertItemPosition.None;
            ListView1.EditIndex = e.NewEditIndex;
            BindData();
        }

        protected void ListView_ItemCanceling(object sender, ListViewCancelEventArgs e)
        {
            if (e.CancelMode == ListViewCancelMode.CancelingEdit)
            {
                ListView1.EditIndex = -1;
                BindData();
            }
            else if(e.CancelMode == ListViewCancelMode.CancelingInsert)
            {
                ListView1.InsertItemPosition = InsertItemPosition.None;
                BindData();
            }
        }

        protected void ListView1_ItemDeleting(object sender, ListViewDeleteEventArgs e)
        {
            long ID = Convert.ToInt64(ListView1.DataKeys[e.ItemIndex].Value.ToString());
            MeasureBLL bll = new MeasureBLL();
            bll.DeleteMeasureSub2(ID);
            BindData();
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            ListView1.EditIndex = -1;//增加的时候不能同时修改
            ListView1.InsertItemPosition = InsertItemPosition.LastItem;         
            BindData();
            ItemData(ListView1.InsertItem);
        }

        protected void btn_ReturnList_Click(object sender, ImageClickEventArgs e)
        {
            string url = string.Format("~/DataEntry/Move_Family/Move_Family_Manage.aspx?type=measure&Potence=NULL&page={0}", Request["page"]);
            Response.Redirect(url);

        }

        protected void btnReport_Click(object sender, EventArgs e)
        {
            string url = string.Format("/Measurement/MainPrint.aspx?url=/DataEntry/PrintMeaSub2New.aspx?familyid={0}",
                                       FamilyId);
            Response.Write("<script language='javascript'>window.open('" + url + "','_blank');</script>");
        }
    }
}
原文地址:https://www.cnblogs.com/wenghaowen/p/3684912.html