[英]C# Windows Forms how to change values of second combo box based on selection in first combo box
I am attempting to create an order form and as such am using combo boxes in order to let the user choose what item is going to be ordered. 我试图创建一个订购单,因此正在使用组合框,以便让用户选择要订购的商品。 As such when the user selects the item that is going to be ordered, the second combo box should change to the sizes that the specific item can be ordered in. I have filled the second combo box with the sizes for all the items but I am unsure as to how to limit the sizes per the item that is selected.
这样,当用户选择要订购的商品时,第二个组合框应更改为可以订购特定商品的尺寸。我已经用所有商品的尺寸填充了第二个组合框,但我是不确定如何限制所选项目的大小。 I have tried using if statements to addRange to the second combo box however this just duplicates the items at the end of the combo box.
我尝试使用if语句将addRange添加到第二个组合框,但是这只是复制了组合框末尾的项目。 any help that can be given on this would be greatly appreciated.
对此可以提供的任何帮助将不胜感激。 Thanks
谢谢
private void itemBox_SelectedIndexChanged(object sender, EventArgs e)
{
switch (((ComboBox)sender).SelectedItem as string)
{
case "Name in a Frame":
sizeBox.SelectedIndex = 0;
break;
case "Scrabble Frame":
sizeBox.SelectedIndex = 1;
break;
case "Plaque":
sizeBox.SelectedIndex = 2;
break;
case "Hearts":
sizeBox.SelectedIndex = 3;
break;
case "Now and Forever Print":
sizeBox.SelectedIndex = 4;
break;
case "Pat cushion":
sizeBox.SelectedIndex = 5;
break;
case "Emilia cushion":
sizeBox.SelectedIndex = 6;
break;
}
}
private void sizeBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (sizeBox.SelectedIndex == 0)
{
this.sizeBox.Items.AddRange(new object[]{
"7x5",
"10x8",
"A4",
"Mug"
});
}
}
You could just populate the sizeBox collection directly from the itemBox selected change event handler and remove sizeBox_SelectedIndexChanged
altogether. 您可以直接从选择的itemBox更改事件处理程序中直接填充sizeBox集合,
sizeBox_SelectedIndexChanged
完全删除sizeBox_SelectedIndexChanged
。
However, to achieve what, you need to clear the items in the sizeBox once the item has been selected. 但是,要实现此目的,选择项目后,需要清除sizeBox中的项目。 You can achieve this via:
您可以通过以下方式实现:
sizeBox.Items.Clear();
You can then add the items once the sizeBox selected index has changed. 然后,一旦sizeBox所选索引已更改,就可以添加项目。 I would simply use:
我只会使用:
sizeBox.Items.Add("New Size");
For good practice I would remove the use of magic strings, maybe put them in a Products helper class that returns the appropriate string. 出于良好做法,我将删除魔术字符串的使用,也许将它们放在返回适当字符串的Products帮助器类中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.