简体   繁体   English

结构和枚举,Combobox.SelectedItem

[英]Struct & Enum, Combobox.SelectedItem

The program is a minidatabase-ish thing for product ordering purposes, where I keep the unique orders in a struct, and the productNames in an enum (for practice basically). 该程序是用于产品订购的小型数据库产品,其中将唯一的订单保留在结构中,将productNames保留在枚举中(基本上用于实践)。 I only have 3 productnames (Product0, Product1, Product2), and they are added to a combobox ( cbo_productNameEdit.DataSource = Enum.GetNames(typeof(productNames)); ). 我只有3个产品名称(Product0,Product1,Product2),并将它们添加到组合框( cbo_productNameEdit.DataSource = Enum.GetNames(typeof(productNames)); )。

Anyway, after saving an order, I want this combobox to change it's selected item to the saved product's name, but it fails to do so. 无论如何,保存订单后,我希望此组合框将其选择的项目更改为保存的产品名称,但是这样做没有成功。 I checked it with a MessageBox, to see if it didn't store it properly... 我用MessageBox进行了检查,看它是否没有正确存储...

MessageBox.Show(Orders[cbo_productID.SelectedIndex].productName.ToString());
cbo_productNameEdit.SelectedItem = Orders[cbo_productID.SelectedIndex].productName;

... the messagebox returned Product2, which is indeed the correct one, but the selected item stayed at Product0. ...消息框返回了Product2,它确实是正确的,但是所选项目仍停留在Product0。

One thing you could do to solve it is to set the SelectedIndex instead of SelectedItem property on the combobox. 解决该问题的一件事是在组合框上设置SelectedIndex而不是SelectedItem属性。 By default Enums are 0 based integers, so the index will corespond to the value of the enum. 默认情况下,Enum是基于0的整数,因此索引将与枚举的值相对应。

cbo_productNameEdit.SelectedIndex = (int)Enum.Parse(typeof(productNames),
                             Orders[cbo_productID.SelectedIndex].productName.ToString());

Because you used .DataSource property for filling ComboBox with items 因为您使用.DataSource属性来为ComboBox填充项目
You need to use .SelectedValue for setting selecting item 您需要使用.SelectedValue设置选择项

cbo_productNameEdit.SelectedValue = Orders[cbo_productID.SelectedIndex].productName;

From MSDN: ComboBox.SelectedValue 从MSDN: ComboBox.SelectedValue

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM