如何添加包含值的标签

时间:2016-04-18 20:53:14

标签: c# winforms

这与列表框和常量有关。

首先,您选择每个"项目"在列表框中。 然后,使用常量,该值将出现在标签中。

        workshop = workshopListBox.SelectedItem.ToString();
        switch (workshop)
        {
            case "Outdoor workshop bundle":
                registrationFeeLabel.Text = OUTDOOR_WORKSHOP_BUNDLE.ToString("c");
                break;
            case "Essential Outdoor Field Skills":
                registrationFeeLabel.Text = ESSENTIAL_OUTDOOR_FIELD.ToString("c");
                break;
            case "Picture Perfect Panoramas":
                registrationFeeLabel.Text = PICTURE_PERFECT_PANORAMAS.ToString("c");
                break;
            case "Night Photography Magic":
                registrationFeeLabel.Text = NIGHT_PHOTOGRAPHY_MAGIC.ToString("c");
                break;

        }

        location = locationListBox.SelectedItem.ToString();
        switch (location)
        {
            case "Mont Tremblant":
                lodgingFeeLabel.Text = MONT_TREMBLANT.ToString("c");
                break;
            case "Quebec":
                lodgingFeeLabel.Text = QUEBEC.ToString("c");
                break;
            case "Montreal":
                lodgingFeeLabel.Text = MONTREAL.ToString("c");
                break;

这里是常量和值:

 const int OUTDOOR_WORKSHOP_BUNDLE = 200;
    const int ESSENTIAL_OUTDOOR_FIELD = 100;
    const int PICTURE_PERFECT_PANORAMAS = 100;
    const int NIGHT_PHOTOGRAPHY_MAGIC = 150;
    const int MONT_TREMBLANT = 75;
    const int QUEBEC = 95;
    const int MONTREAL = 0;
    string workshop;
    string location;

我将如何"保持"用户选择的标签中的值是什么,并将其与用户选择的另一个值相加?谢谢

2 个答案:

答案 0 :(得分:0)

您不想在标签中添加值,这样就会出现奇怪的错误,因为转换会出错。

相反,您已经有办法找到给定ListBox选项的数值,您应该使用它。

答案 1 :(得分:0)

您不应在标签和列表框中执行业务逻辑。我建议你为研讨会项目创建一个课程

public class Workshop
{
    public string Name { get; set; }
    public decimal Price { get; set; }

     // Visual Studio 2015 / C#6.0 syntax.
    public override string ToString() => $"{Name} ({Price:c})";
}

现在您可以使用

创建列表
List<Workshop> workshops = new List<Workshop> {
    new Workshop { Name = "Outdoor workshop bundle", Price = 200m },
    new Workshop { Name = "Essential Outdoor Field Skills", Price = 100m},
    ...
};

将列表分配到列表框

workshopListBox.DataSource = workshops;

选择这样的选定项目

var item = (Workshop)workshopListBox.SelectedItem;

并在总和字段中加上价格

decimal sum = 0.0m;  // Make it a field, not a local variable.

...

sum += item.Price;
registrationFeeLabel.Text = sum.ToString("c");

现在,因为Workshop项目包含名称和价格,并且因为列表框包含Workshop项目而不仅仅是字符串,所以不再需要case语句。覆盖ToString方法很重要。列表框需要它才能知道如何显示项目。