Hi, I've got a DropDownList with a list of colours, when one is selected and the "Add to ShoppingCart" button is pressed, all the colours in the DropDownList are duplicated.

Can somebody please help.

// fill the control with data
    private void PopulateControls(ProductDetails pd)
    {
            // display product recommendations
        string productId = pd.ProductId.ToString();
        recommendations.LoadProductRecommendations(productId);
   
            // display the product details
        titleLabel.Text = pd.Name;
        descriptionLabel.Text = pd.Description;
        priceLabel.Text = String.Format("{0:c}", pd.Price);
        productImage.ImageUrl = "ProductImages/" + pd.Image2FileName;
            // set the title of the page
        this.Title = BalloonShopConfiguration.SiteName + pd.Name;

            // obtain the attributes of the product
        DataTable attrTable = CatalogAccess.GetProductAttributes(productId);

            // temp variables
        string prevAttributeName = "";
        string attributeName, attributeValue, attributeValueId;

            // current DropDown for attribute values
        Label attributeNameLabel;
        DropDownList attributeValuesDropDown = new DropDownList();

            // read the list of attributes
        foreach (DataRow r in attrTable.Rows)
        {
                // get attribute data
            attributeName = r["AttributeName"].ToString();
            attributeValue = r["AttributeValue"].ToString();
            attributeValueId = r["AttributeValueID"].ToString();

                // if starting a new attribute (e.g. Color, Size)
            if (attributeName != prevAttributeName)
            {
                prevAttributeName = attributeName;
                attributeNameLabel = new Label();
                attributeNameLabel.Text = attributeName + ": ";
                attributeValuesDropDown = new DropDownList();
                attrPlaceHolder.Controls.Add(attributeNameLabel);
                attrPlaceHolder.Controls.Add(attributeValuesDropDown);
            }
                // add a new attribute value to the DropDownList
            attributeValuesDropDown.Items.Add(new ListItem(attributeValue, attributeValueId));
        }
    }

    protected void AddToCartButton_Click(object sender, EventArgs e)
    {
            // Retrieve ProductID from the query string
        string productId = Request.QueryString["ProductID"];

            // Retrieve the selected product options
        string options = "";
        foreach (Control cnt in attrPlaceHolder.Controls)
        {
            if (cnt is Label)
            {
                Label attrLabel = (Label)cnt;
                options += attrLabel.Text;
            }

            if (cnt is DropDownList)
            {
                DropDownList attrDropDown = (DropDownList)cnt;
                options = attrDropDown.Items[attrDropDown.SelectedIndex].Value;
            }
        }

        // Add the product to the shopping cart
        ShoppingCartAccess.AddItem(productId, options);

    }

Dani AI

Generated

Short diagnosis and why you saw duplicates: the DropDownLists are created and filled every request while ASP.NET is also restoring their state, so the saved items get reused and your code then appends the same items again. That is why suggested using IsPostBack, suggested clearing the list, and why disabling EnableViewState (which you tried) stopped the duplication — it prevented the old items from being restored so only the freshly-built items remained.

A more robust approach is to recreate the dynamic controls on every request early in the lifecycle (OnInit/Page_Init) with stable IDs, and then bind their data only on the first load (or explicitly clear before binding). That lets the runtime restore postback data correctly and prevents accidental double-appending. Example pattern (conceptual):

protected override void OnInit(EventArgs e) {
  base.OnInit(e);
  CreateAttributeControls();   // always recreate controls with the same IDs
}

protected void Page_Load(object sender, EventArgs e) {
  if (!IsPostBack) BindAttributeData(); // fill items only once when using viewstate
}

If you prefer to rebuild lists on every request, keep EnableViewState=false for those DropDownLists and repopulate them each time — that is a valid tradeoff, but ensure controls are recreated in Init so posted selections still bind correctly. Always give each dynamic DropDown a consistent ID (sanitize names) and either call Items.Clear() before adding, or only bind when Items.Count==0.

One more bug to fix in the Add-to-cart logic: the code as posted overwrites the options string for each DropDown instead of appending. Use a StringBuilder or += and include separators so the final options contains all chosen attribute values rather than just the last one.

Recommended Answers

All 7 Replies

Do not load data into dropdown when a page is posted back.

if(!IsPostBack) {
     //load data into dropdownlist
  }

You can also clear your list depending on how youre going to use it

DropDownList attributeValuesDropDown = new DropDownList();
attributeValuesDropDown.Clear();

This will clear it out each time it runs. The above method also works but if the list is created dynamically, it wont appear at all after the page loads. Clearing it ensures it will always be clean. The after submits query the submission.

Thanks for the replies, I tried the if(!IsPostBack), this just made the DropDownList disappear after the “Add to cart” button is pressed.

I tried attributeValuesDropDown.Clear(); as well, first it didn’t recognize the Clear() command so I used ClearSelection() which did not change anything.

Please post your complete code here. One more suggestion - Set EnableViewState property of DropDownList to false (do not use IsPostBack) or Invoke Clear() method of Items collection of dropdownlist. (DropDownList1.Items.Clear())

I disable the EnableViewState and it works perfect now, Thank you very much!!!

Please someone help with shopping cart codes. Thank u very much

Hi, I've got a DropDownList with a list of colours, when one is selected and the "Add to ShoppingCart" button is pressed, all the colours in the DropDownList are duplicated.

Can somebody please help.

// fill the control with data
    private void PopulateControls(ProductDetails pd)
    {
            // display product recommendations
        string productId = pd.ProductId.ToString();
        recommendations.LoadProductRecommendations(productId);
   
            // display the product details
        titleLabel.Text = pd.Name;
        descriptionLabel.Text = pd.Description;
        priceLabel.Text = String.Format("{0:c}", pd.Price);
        productImage.ImageUrl = "ProductImages/" + pd.Image2FileName;
            // set the title of the page
        this.Title = BalloonShopConfiguration.SiteName + pd.Name;

            // obtain the attributes of the product
        DataTable attrTable = CatalogAccess.GetProductAttributes(productId);

            // temp variables
        string prevAttributeName = "";
        string attributeName, attributeValue, attributeValueId;

            // current DropDown for attribute values
        Label attributeNameLabel;
        DropDownList attributeValuesDropDown = new DropDownList();

            // read the list of attributes
        foreach (DataRow r in attrTable.Rows)
        {
                // get attribute data
            attributeName = r["AttributeName"].ToString();
            attributeValue = r["AttributeValue"].ToString();
            attributeValueId = r["AttributeValueID"].ToString();

                // if starting a new attribute (e.g. Color, Size)
            if (attributeName != prevAttributeName)
            {
                prevAttributeName = attributeName;
                attributeNameLabel = new Label();
                attributeNameLabel.Text = attributeName + ": ";
                attributeValuesDropDown = new DropDownList();
                attrPlaceHolder.Controls.Add(attributeNameLabel);
                attrPlaceHolder.Controls.Add(attributeValuesDropDown);
            }
                // add a new attribute value to the DropDownList
            attributeValuesDropDown.Items.Add(new ListItem(attributeValue, attributeValueId));
        }
    }

    protected void AddToCartButton_Click(object sender, EventArgs e)
    {
            // Retrieve ProductID from the query string
        string productId = Request.QueryString["ProductID"];

            // Retrieve the selected product options
        string options = "";
        foreach (Control cnt in attrPlaceHolder.Controls)
        {
            if (cnt is Label)
            {
                Label attrLabel = (Label)cnt;
                options += attrLabel.Text;
            }

            if (cnt is DropDownList)
            {
                DropDownList attrDropDown = (DropDownList)cnt;
                options = attrDropDown.Items[attrDropDown.SelectedIndex].Value;
            }
        }

        // Add the product to the shopping cart
        ShoppingCartAccess.AddItem(productId, options);

    }

write poppulatecontrols function in If(!ispostback) if u already write in If(!ispostback) then add a line

attributeValuesDropDown .Items.clear()

before this line attributeValuesDropDown.Items.Add(new ListItem(attributeValue, attributeValueId));

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.