C# Windows Form - How do I assign a double value to a combo box string to then be displayed in a text box? -
i've been having trouble of finding solution coding problem of assigning double value combo box item double value displayed , added text box.
for instance, beverages combo box contains: soda, tea, coffee, milk, juice, etc. "soda" give value of $1.95 displayed in "subtotal:" text box. every time item selected in combo box, soda, juice, , coffee, every time item selected add previous subtotal value in text box.
sorry if isn't clear great, i've blanked out , been trying come solution while , been struggling. thank you!
this perfect use of custom type. in case create drink class description property , price property. override .tostring() method display description.
class drink { public string description { get; set; } public decimal price { get; set; } public override string tostring() { return description; } }
from instantiate new drink, populate description , price , add object combobox. combobox display "soda" object holds 1.95 in price property.
private void form1_load(object sender, eventargs e) { //for demonstration purposes, we're creating 3 drink //objects , adding them combobox. //you loop through data source of sort //and populate combobox newly intantiated objects. drink item; item = new drink(); item.description = "soda"; item.price = 1.80m; combobox1.items.add(item); item = new drink(); item.description = "coffee"; item.price = .95m; combobox1.items.add(item); item = new drink(); item.description = "tea"; item.price = .65m; combobox1.items.add(item); }
since combobox holding object, need cast selecteditem drink have access price selection.
private void button1_click(object sender, eventargs e) { decimal itemprice; //if textbox empty or cannot parsed decimal //then cast combobox1.selecteditem drink type //place value textbox. if, however, can //parsed decimal grab value , add //price of our newly selected combobox item price //that in textbox. if(decimal.tryparse(textbox1.text, out itemprice)) { textbox1.text = (itemprice + ((drink)(combobox1.selecteditem)).price).tostring(); } else { textbox1.text = (((drink)(combobox1.selecteditem)).price).tostring(); } }
Comments
Post a Comment