Hi,
i am trying to edit a list box item in a way that if certain item is already present it should update it and if item is not present then it should add it to a list box what should i do

Detailed
i have a dynamic button which is associated with the products in product table that mean i would be having as much buttons as products i have now on click event i want to add them to a list box in the same cenerio as i explained above

here's my logic and code
i have added up an extra property to hold click count (as name and tag property has already been reserved) if the count is one then it should add item and if count is greater than one then it should update existing but i am stuck how to update it

while (reader.Read())
                    {
                        MyButton b = new MyButton();
                        b.Quantity = 1;
                        b.Text = reader.GetString(2);
                        b.Tag = reader.GetDecimal(6);
                        b.Click += new EventHandler(UpdateProductList);
                    }

                     void UpdateProductList(object sender, EventArgs e)
        {
            MyButton b = (MyButton)sender;
            int Qty = b.Quantity;
            string Name = (string)b.Text;
            double Price = Convert.ToDouble(b.Tag);
            if (Qty == 1)
            {
                ListBoxItem newItem = new ListBoxItem();
                newItem.Price = (decimal)Price;
                newItem.Name = Qty + " " + Name + Price;
                lbProductChoosen.Items.Add(newItem);
                lbProductChoosen.DisplayMember = "Name";
            }
            else 
            {
                Price = Qty * Price;
                ListBoxItem newItem = new ListBoxItem();
                newItem.Price = (decimal)Price;
                newItem.Name = Qty + " " + NamePadded + PriceFormated;

                //how to update an existing item???

            }
            b.Quantity++;
        }

or any one has better idea then that

Edited 3 Years Ago by de Source

Of course it is -- you just need to figure out how to do it. Your program needs to iterate through all the rows of the listbox until it either finds the row that contains the search text (Name) or there are no more items. If it does not find the correct button then just add a new one to the listbox.

I'm no C# expert so I won't show you any code. But it sounds like a pretty trivel thing to do. I don't think you want to check for Qty == 1 like you do on line 16. Just look for a row that contains the Name. The value of Qty should not have anything to do with the search.

This article has been dead for over six months. Start a new discussion instead.