Inserting values into comboBoxes
I want to use a comboBox in a form that allows users to select the pizza size. I can fill in the comboBox with the strings "small", "Medium", "Large", etc., but I want to associate a price to each string. So a "small" would be $7.99, medium would be 12.99 etc.
So how do I add a value to the string in each item?
Here is what I have so far:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace fff
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
comboBox1.Items.Add("Small");
comboBox1.Items.Add("Medium");
comboBox1.Items.Add("Large");
comboBox1.Items.Add("Extra Large");
comboBox2.Items.Add("East End location");
comboBox2.Items.Add("West End location");
comboBox2.Items.Add开发者_运维知识库("South End location");
comboBox2.Items.Add("Downtown location");
comboBox2.Items.Add("North End location");
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void label7_Click(object sender, EventArgs e)
{
}
private void submit_btn_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex == 0)
MessageBox.Show(small);
}
}
}
The best approach would be to create a dictionary and assign it as the DataSource for the combobox, like:
using System;
using System.Collections.Generic;
class Program
{
private void SetValues()
{
var pizzaChoices = new Dictionary<string, double>();
pizzaChoices.Add("Small", 6.99);
pizzaChoices.Add("Medium", 8.99);
pizzaChoices.Add("Large", 11.99);
comboBox1.DataSource = new BindingSource(pizzaChoices, null);
comboBox1.DisplayMember = "Value";
comboBox1.ValueMember = "Key";
}
}
This way, the user sees ("Small", "Medium", "Large") but the value selected would be the double assigned to each entry (KeyValuePair).
More information.
Edit: The same could be done using a custom class:
public class Choices
{
public string Name { get; set; }
public double Price { get; set; }
}
class Program
{
private void SetValues(Choices choices)
{
var list = new List<Choices>(choices);
comboBox1.DataSource = list;
comboBox1.ValueMember = "Price";
comboBox1.DisplayMember = "Name";
}
}
Create an object that wraps up the NAME, PRICE, and any other information you want to store. Set the TOSTRING of that object to return the name. Then, create instances of those objects and add them to the list.
IE:
public class MyStuff{
public string Name {get;set;}
public double Price {get;set;}
public override ToString() { return this.Name; }
}
pizzaValues.Add(new MyStuff {... });
This gives you the ability to store as much information as you want
精彩评论