0

以下に価格を追加する方法を教えてください。

private void OrderForm_Load(object sender, EventArgs e)
{
    comboBox1.Items.Add("0");
    comboBox1.Items.Add("10");
    comboBox1.Items.Add("20");
    comboBox1.Items.Add("30");
    comboBox1.Items.Add("40");
    comboBox1.Items.Add("50");
    comboBox1.Items.Add("60");
    comboBox1.Items.Add("70");
    comboBox1.Items.Add("80");
    comboBox1.Items.Add("90");
    comboBox1.Items.Add("100");
    comboBox2.Items.Add("None");
    comboBox2.Items.Add("Chocolate");
    comboBox2.Items.Add("Vanilla");
    comboBox2.Items.Add("Strawberry");
    comboBox3.Items.Add("Paypal");
    comboBox3.Items.Add("Visa Electron");
    comboBox3.Items.Add("MasterCard");
    comboBox4.Items.Add("None");
    comboBox4.Items.Add("Small");
    comboBox4.Items.Add("Medium");
    comboBox4.Items.Add("Large");
}

「0〜100」の数字の価格はそれぞれ「£15」である必要がありますか?

4

2 に答える 2

4

コンボボックスには、ToStringメソッドの結果がアイテムの名前として表示されます。これは、名前と価格を含む独自のオブジェクトを作成し、オーバーライドToStringして名前のみを表示できることを意味します。例えば:

public class MyItem
{
    private readonly string name;
    public string Name
    {
        get { return this.name; }
    }

    private readonly decimal price;
    public decimal Price
    {
        get { return this.price; }
    }

    public MyItem(string name, decimal price)
    {
        this.name = name;
        this.price = price;
    }

    public override string ToString()
    {
        return this.name;
    }
}

次に、独自のオブジェクトを作成して追加します。

comboBox2.Items.Add(new MyItem("Chocolate", 10.00m));
comboBox2.Items.Add(new MyItem("Vanilla", 15.00m));
comboBox2.Items.Add(new MyItem("Strawberry", 8.50m));

コンボボックスからアイテム(たとえば、現在選択されているアイテム)を取得するたびに、Priceプロパティから価格が通知されます。例えば:

MyItem selectedItem = (MyItem)comboBox2.SelectedItem;
decimal totalPrice = selectedItem.Price + 1.00m /* Shipping */;
于 2013-03-11T23:22:58.247 に答える
0

質問に直接答えるには、次のようにComboBox.SelectedIndex値を使用できます。

if (comboBox4.SelectedIndex < 100) {
    price = 15;
}

しかし、私はそれを私のコードには入れません。このようにコードを書くと「メンテナンスの地獄」と叫ぶので、コードの再構築を検討してください。オブジェクト指向を使用して名前/価格を格納するというMartinのソリューションに沿って提案するつもりだったので、試してみることをお勧めします。

于 2013-03-11T23:40:27.620 に答える