c# 使用多个列表框

c# using multiple listbox

我有 2 个列表框和 2 个文本框,我需要它做的是,如果我单击列表框 1 中的一个项目,它会在列表框 2 中显示 2 个或更多项目,如果我单击列表框 2 中的一个项目将是一个操作,它将出现在文本框 1 和文本框 2 中, 前任。圆珠笔=10,笔记本=20

"listBox1" 中包含的项目是 "pen" 和 "notebook"。如果我单击笔记本,列表框 2 中将显示一个项目:1,2 然后如果我单击“1”,文本框 1.text=20 因为笔记本是 20*1=20

我想你可以用一个字典来存储listBox1和listBox2的信息。 key 是 listBox1 中的一个项目,value 是 listBox2 中的列表项。当您单击 listBox1 中的项目时 => 调用 listBox1 的 SelectedIndexChanged 事件 => 获取您选择的项目(assume = value1) => 在字典中查找 key = value1 => 您将在 listBox2 中获得列表项(assume = listItems) = > 将 listItems 添加到 listBox2 => 当您单击 listBox2 中的项目时调用 listBox2 的 SelectedIndexChanged 事件 => 更新 textbox1 和 textbox2 的值 = 在 listBox1 和 listBox2 中选择了项目。

所以,我将为您的项目创建一个枚举。

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

然后我会将这些添加到表单构造函数中的 "listBox1"。

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

然后使用此过程为 textBox1 进行计算:

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