Can't get Value from ComboBox

前端 未结 6 2136
时光取名叫无心
时光取名叫无心 2021-01-15 16:04

I have a simple comboBox with some Value/Text items in it. I have using ComboBox.DisplayMember and ComboBox.ValueMember to correctly set the value/text. When I try to get th

6条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-15 16:45

    As you have seen in the debugger, SelectedItem contains the information you need. But to access SelectedItem.Value, you need to cast SelectedItem to the appropriate type (which is problematic if you are using an anonymous type) or use reflection. (VS can't compile SelectedItem.Value because at compile time VS only knows that SelectedItem is of type Object, which doesn't have a Value property.)

    To use reflection to get the Value member, use Type.InvokeMember with BindingFlags.GetProperty.

    To cast SelectedItem, declare a named type with Value and Text properties instead of using an anonymous type, and add instances of the named type to the ComboBox, instead of instances of the anonymous type. Then cast SelectedItem: ((MyType)(cb.SelectedItem)).Value.

提交回复
热议问题