如何使用另一个数组中的索引获取数组中的位置?

时间:2013-05-16 17:37:30

标签: c# arrays

我正在创建一个应用程序,用户可以选择比萨饼和饮料。 我使用数组列表进行披萨选择 从表单中使用复选框;如果检查了所有5个复选框,那么我需要做什么,然后从数组中获取所有数据

这是类

中的代码
namespace order
{
    class Menu
    {
        string[] pizza = {"Cheese and Ham", "Ham and Pineapple", "Vegetarian", "MeatFeast", "Seafood" };
        double[] price = {3.50, 4.20, 5.20, 5.80, 5.60 };

        public string GetMenuItem(int select)
        {
            string choice = pizza[select];
            return choice;
        }


这是表格代码

namespace order

{
    public partial class Form1 : Form
    {

        Menu menuMaker = new Menu();
        public Form1()
        {
            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {


            if (checkBox1.Checked)
            {
               label1.Text = menuMaker.GetMenuItem(0);
            }


        }
    }

如果选中一个,则表单会显示该结果,但如果我想选中所有复选框,则需要显示所有结果。

2 个答案:

答案 0 :(得分:1)

解决此问题的一种方法是从Label切换到ListView。然后,您可以添加已选择的项目。如果他们选择3,则添加3,如果他们选择全部5,则添加全部5个。

使用listview的示例 -

public partial class Form1 : Form
{
    Menu menuMaker = new Menu();
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        listView.Clear();

        if (checkBox1.Checked)
        {
           listView.Items.Add(menuMaker.GetMenuItem(0));
        }
        if (checkBox2.Checked)
        {
           listView.Items.Add(menuMaker.GetMenuItem(1));
        }
    }
}

暂且不说。您可能需要考虑为包含价格的比萨创建一个帮助程序类。像 -

这样的东西
class MyMenuItem
{
    public string Name { get; set; }
    public double Price { get; set; }
}

您只能拥有一系列菜单项,并且您可以将价格和名称放在一个类中。

进一步建议 - 您可以考虑将Menu课程重命名为MyMenu,以使其与System.Windows.Forms.Menu课程不冲突。

答案 1 :(得分:0)

更好,但也不好,你必须添加panel1到形式:

    public Form1()
    {
        InitializeComponent();
        list = new List<CheckBox>();
    }
    List<CheckBox> list;
    Menu menu;
    private void Form1_Load(object sender, EventArgs e)
    {
        menu = new Menu();
        int i = 10;
        foreach(var item in menu.pizza){
            CheckBox checkBox = new CheckBox();
            checkBox.Text = item;
            checkBox.Location = new System.Drawing.Point(10, i);
            i = i + 30;
            list.Add(checkBox);
            panel1.Controls.Add(checkBox);
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < list.Count;i++ )
        {
            if (list[i].Checked)
            {
                label1.Text += menu.GetMenuItem(i);
            }
        }
    }
}

并更改菜单:

class Menu
{
    public readonly string[] pizza = { "Cheese and Ham", "Ham and Pineapple", "Vegetarian", "MeatFeast", "Seafood" };
    public readonly double[] price = { 3.50, 4.20, 5.20, 5.80, 5.60 };

    public string GetMenuItem(int select)
    {
        string choice = pizza[select];
        return choice;
    }
}
相关问题