ASP.Net应用程序在回发上加倍控制

时间:2018-03-28 01:56:30

标签: c# asp.net

当我的页面点击回发时,我最终会在我的页面上加倍控件。控件的前半部分都包含原始值和所有文本框中列出的新值,第二组仅包含所有旧值。当单步执行我的代码时,它似乎没有遇到同样的问题,但是每次都会正常运行它。

这是我的Page_Load:

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["UserID"] != null)
            {
                if (Convert.ToInt16(Session["level"]) == 0)
                {
                    FillStoreDropDown();
                    FillTypeDropDown();
                }
                else
                {
                    Response.Redirect("~/LoginPage.aspx");
                }
            }
            else
            {
                Response.Redirect("~/LoginPage.aspx");
            }
        }

        addProductElements();

        if (!IsPostBack)
        {
            if (Session["LoadExisting"] != null)
            {
                LoadExisting();
                CheckType();
            }
        }
    }

addProductElements()每次运行时只创建一组控件,并且每隔一段时间运行一次。这个问题实际出现的唯一时间是我运行一个save方法,然后更改文本框中的值。下面是我的textbox_changed代码以及我正在使用的递归搜索:

        // finds controls that were created dynamically
    private Control FindControlRecursive(Control rootControl, string controlID)
    {
        if (rootControl.ID == controlID) return rootControl;

        foreach (Control controlToSearch in rootControl.Controls)
        {
            Control controlToReturn = FindControlRecursive(controlToSearch, controlID);
            if (controlToReturn != null) return controlToReturn;
        }
        return null;
    }

    // to update total label after typing in a product count check box
    protected void productCount_TextChanged(object sender, EventArgs e)
    {
        int num = myPanel.Controls.Count;
        string myString = (((Control)sender).Parent.ID).ToString();

        myString = Regex.Replace(myString, "[^0-9]", "");

        Label totalPrice = (Label)FindControlRecursive(Page, ("lblProdSumTotal" + myString));
        Label prodPrice = (Label)FindControlRecursive(Page, ("lblProdPrice" + myString));
        TextBox prodCount = (TextBox)FindControlRecursive(Page, ("txtProdCount" + myString));
        Label promoDiscount = (Label)FindControlRecursive(Page, ("lblPromoDisc" + myString));

        int n;
        if (int.TryParse(prodCount.Text, out n))
        {
            if (promoDiscount.Text != "")
            {
                totalPrice.Text = ((Convert.ToDecimal(prodCount.Text)) * ((Convert.ToDecimal(prodPrice.Text)) - (Convert.ToDecimal(promoDiscount.Text)))).ToString("c");

            }
            else
            {
                totalPrice.Text = ((Convert.ToDecimal(prodCount.Text)) * (Convert.ToDecimal(prodPrice.Text))).ToString("c");

            }
            UpdateIndLabelTotal();
        }
        else
        {
            lblNotice.Attributes.Add("style", "label-danger");
            lblNotice.Text = "Invalid entry.";
        }
    }

编辑:这是addProductElements():

        protected void addProductElements()
    {

        // set up an array of all products through sql connection
        SqlDataReader reader = null;
        SqlConnection connection = null;
        SqlCommand command = null;

        String queryString;

        List<string> allProducts = new List<string>();
        List<string> allUPCs = new List<string>();
        List<string> allPrices = new List<string>();
        List<List<string>> promotionItems = new List<List<string>>();

        queryString = @"SELECT products.productid, products.upc, products.productname, products.sapnum, products.price FROM Products order by products.productname";
        connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Test"].ConnectionString);
        command = new SqlCommand(queryString, connection);

        connection.Open();

        reader = command.ExecuteReader();

        while (reader.Read())
        {
            allProducts.Add(reader["ProductName"].ToString());
            allUPCs.Add(reader["UPC"].ToString());
            allPrices.Add(reader["Price"].ToString());
        }

        reader.Close();
        connection.Close();

        queryString = @"SELECT * FROM Promotions WHERE StoreID = @StoreID and StartDate <= getdate() and EndDate >= getdate()";
        connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Test"].ConnectionString);
        command = new SqlCommand(queryString, connection);
        command.Parameters.AddWithValue("storeID", Convert.ToInt16(ddlCompanyStores.SelectedValue));
        connection.Open();
        reader = command.ExecuteReader();
        while (reader.Read())
        {
            List<string> tempList = new List<string>();
            tempList.Add(reader["PromotionID"].ToString());
            tempList.Add(reader["StoreID"].ToString());
            tempList.Add(reader["Parent_CompanyID"].ToString());
            tempList.Add(reader["UPC"].ToString());
            tempList.Add(reader["DiscountAmount"].ToString());
            tempList.Add(reader["StartDate"].ToString());
            tempList.Add(reader["EndDate"].ToString());
            promotionItems.Add(tempList);
        }
        reader.Close();
        connection.Close();

        string[] myProds = allProducts.ToArray();

        // set up a loop
        // for each in loop, create controls with loop index name id
        // add each to array

        PlaceHolder PlaceHolder1 = new PlaceHolder();

        int numlabels = myProds.GetUpperBound(0);
        for (int i = 0; i <= numlabels; i++)
        {
            Panel prodPanel = new Panel();
            Label productName = new Label();
            Label productID = new Label();
            TextBox productCount = new TextBox();
            Label productOperator = new Label();
            Label productPrice = new Label();
            Label promotionOperator = new Label();
            Label promotionDiscount = new Label();
            Label productSumVal = new Label();
            Label productSumTotal = new Label();

            prodPanel.ID = "Panel" + i.ToString();
            prodPanel.Attributes.Add("style", "background-color: #E7E4E3;margin-top:15px;padding-top:10px");
            prodPanel.Attributes.Add("Class", "container");

            productName.Text = allProducts[i];
            productName.Attributes.Add("style", "float:left");
            productName.ID = "lblProdName" + i.ToString();
            prodPanel.Controls.Add(productName);

            productID.Text = allUPCs[i];
            productID.Attributes.Add("style", "float:right");
            productID.ID = "lblProdID" + i.ToString();
            prodPanel.Controls.Add(productID);

            prodPanel.Controls.Add(new LiteralControl("<br />"));

            productCount.Text = "0";
            productCount.Attributes.Add("style", "float:left");
            productCount.ID = "txtProdCount" + i.ToString();
            productCount.AutoPostBack = true;
            productCount.Attributes.Add("type", "number");
            productCount.TextChanged += new EventHandler(productCount_TextChanged);

            prodPanel.Controls.Add(productCount);

            productOperator.Text = " x ";
            productOperator.Attributes.Add("style", "float:left");
            productOperator.ID = "lblProdOper" + i.ToString();
            prodPanel.Controls.Add(productOperator);

            productPrice.Text = allPrices[i];
            productPrice.Attributes.Add("style", "float:left");
            productPrice.ID = "lblProdPrice" + i.ToString();
            prodPanel.Controls.Add(productPrice);

            promotionOperator.Text = "";
            promotionOperator.Attributes.Add("style", "float:left");
            promotionOperator.ID = "lblPromoOper" + i.ToString();
            prodPanel.Controls.Add(promotionOperator);

            promotionDiscount.Text = "";
            promotionDiscount.Attributes.Add("style", "float:left");
            promotionDiscount.ID = "lblPromoDisc" + i.ToString();
            prodPanel.Controls.Add(promotionDiscount);

            foreach (List<string> l in promotionItems)
            {
                if (l[1] == ddlCompanyStores.SelectedValue)
                {
                    if (l[3] == allUPCs[i])
                    {
                        promotionOperator.Text = " - ";

                        promotionDiscount.Text = Convert.ToDecimal(l[4]).ToString();
                    }
                }
            }

            productSumVal.Text = " = ";
            productSumVal.Attributes.Add("style", "float:left");
            productSumVal.ID = "lblProdSum" + i.ToString();
            prodPanel.Controls.Add(productSumVal);

            productSumTotal.Text = "$0.00";
            productSumTotal.Attributes.Add("style", "float:right");
            productSumTotal.ID = "lblProdSumTotal" + i.ToString();
            prodPanel.Controls.Add(productSumTotal);

            myPanel.Controls.Add(prodPanel);
            myPanel.Controls.Add(new LiteralControl("<br />"));
        }
    }

1 个答案:

答案 0 :(得分:0)

任何时候页面加载Page_Load都会起作用。 所以你使用;

addProductElements();

if(!IsPostBack)不在protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { if (Session["UserID"] != null) { if (Convert.ToInt16(Session["level"]) == 0) { FillStoreDropDown(); FillTypeDropDown(); } else { Response.Redirect("~/LoginPage.aspx"); } } else { Response.Redirect("~/LoginPage.aspx"); } addProductElements(); if (Session["LoadExisting"] != null) { LoadExisting(); CheckType(); } } } 内,因此无论何时页面加载都会有效。是否是回发。

{{1}}