Search code examples
c#listboxlistboxitemoperation

c# using multiple listbox


I have 2 ListBoxes and 2 TextBoxes, what I need it to do is if I click an item in list box 1 it shows 2 or more items in list box 2 and if I click an item in list box 2 there will be an operation and it will appear in text box 1 and text box 2, ex. ballpen=10,notebook=20

The items included in "listBox1" are the "pen" and "notebook". If I click notebook an item will show in list box 2: 1,2 then if I click "1", text box 1.text=20 because notebook is 20*1=20


Solution

  • So, I'm just going to create an enumeration for your items.

    public enum ListBoxItemThing
    {
        Pen = 10, Notebook = 20
    }
    

    And then I'll add these to "listBox1" inside the form constructor.

    public Form1()
    {
        InitializeComponent();
        foreach(ListBoxItemThing item in Enum.GetValues(typeof(ListBoxItemThing)))
        {
            listBox1.Items.Add(item);
        }
    }
    

    And then use this procedure to do the calculation for textBox1:

    private void Calculate()
    {
        int a = (int)(listBox1.SelectedItem as ListBoxItemThing);
        int b = int.Parse(listBox2.SelectedItem.ToString());
        textBox1.Text = (a * b).ToString();
    }