c# - How to combine the product when the same and when add in a list box? -


how combine product when same?
how sum of price?
if not same product add in list box.
if same product combine , sum of price combine.

here's code program. ^_^;

public partial class form1 : form {     public form1()     {         initializecomponent();     }      private void btnadd_click(object sender, eventargs e)     {         string product = txtproduct.text;         decimal price = convert.todecimal(txtprice.text);          lstproductpricebox.items.add(             product + " = " + price.tostring("c")); // how combine product when same? ,                                                    //  how sum of price?                                                    // if not same product add in list box                                                    // if same product combine , sum price.     }       private void btnexit_click(object sender, eventargs e)     {         this.close();     } } 

you need define product class contains productname , price. here's code:

public partial class form1 : form {     list<product> source;      public form1()     {         initializecomponent();     }      private void form1_load(object sender, eventargs e)     {         source = new list<product>();     }      private void button1_click(object sender, eventargs e)     {         decimal price;         if (string.isnullorempty(txtproduct.text) || !decimal.tryparse(txtprice.text, out price))         {             messagebox.show("invalid values!");             return;         }         var existingproduct = source.where(x=> x.productname==txtproduct.text).singleordefault();         if(existingproduct!=null)         {             existingproduct.price += price;          }         else             source.add(new product {price = price, productname = txtproduct.text} );          listbox1.datasource = null;         listbox1.datasource = source;     }   }  public class product {     public string productname { get; set; }     public decimal price { get; set; }      public override string tostring()     {         return string.format("{0} = {1}", productname, price.tostring("c"));     } } 

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -