我似乎找不到一个易于使用的.net本地方式来获取.net winforms上的Comboboxes来显示一个值并根据选择返回另一个值而不创建我自己的帮助类,知道winforms将要显示放在其中的对象上的ToString方法.
这就是我现在正在做的事情,非常一般.首先,创建辅助类.
Public Class ListItem Public Value As Object Public DisplayString As String Public Sub New(ByVal NewValue As Object, ByVal NewDisplayString As String) Value = NewValue DisplayString = NewDisplayString End Sub Public Overrides Function ToString() As String Return DisplayString End Function End Class
然后,从集合或其他任何东西加载组合框.
For Each o as WhateverObject In CollectionIwantToaddItemsFrom li = New ListItem(o.ValueToReturn, o.ValueToDisplay) Me.ComboBox1.Items.Add(li) Next
最后,使用该对象
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ComboBox1.SelectedIndexChanged if me.combobox1.selecteditem is nothing then exit sub Dim li As ListItem = me.ComboBox1.SelectedItem Dim o as object = li.value 'do stuff with o. end sub
我敢肯定,在我正在寻找的框架中,我最好使用一些东西.它是什么?
这有点像黑客,但这意味着你不必编写自己的Name-Value对类 - 没什么大不了的(可能在框架中已经有了更好的东西).但你可以做的是使用DictionaryEntry类 - 它实际上是一个名称值对.将项添加到列表中,然后使用组合框上的DataMember和ValueMember属性绑定到DictionaryEntry类的键和值属性.像这样:
var list = new List(); list.Add(new System.Collections.DictionaryEntry("one", 1)); list.Add(new System.Collections.DictionaryEntry("two", 2)); list.Add(new System.Collections.DictionaryEntry("three", 3)); comboBox1.DataSource = list; comboBox1.DisplayMember = "Key"; comboBox1.ValueMember = "Value";
刚刚意识到你更喜欢vb方言.以下对VB也是如此:-)
Dim list As List(Of DictionaryEntry) list = New List(Of DictionaryEntry) list.Add(New DictionaryEntry("One", 1)) list.Add(New DictionaryEntry("Two", 2)) list.Add(New DictionaryEntry("Three", 3)) ComboBox1.DataSource = list ComboBox1.DisplayMember = "Key" ComboBox1.ValueMember = "Value"