当您填充组合时,会用通常以代码和描述形式出现的数据加载该组合,但是组合仅对描述感兴趣。 通过创建从组合继承而来的类以及其他属性,您还可以使用它来保留代码。 当用户选择描述时,您可以从控件中获取代码。 这是我的方法:
Public Class ComboControl : Inherits System.Windows.Forms.ComboBox
Private _CodeDescriptions As New Dictionary(Of String, String)
Private _DescriptionCodes As New Dictionary(Of String, String)
Private _AllowNone As Boolean
Private _AllowAny As Boolean
Private _ContextFlag As String
Public Sub Clear()
_CodeDescriptions.Clear()
_DescriptionCodes.Clear()
Me.Items.Clear()
End Sub
Public Property AllowAny() As Boolean
Get
AllowAny = _AllowAny
End Get
Set(ByVal value As Boolean)
_AllowAny = value
End Set
End Property
Public Property AllowNone() As Boolean
Get
AllowNone = _AllowNone
End Get
Set(ByVal value As Boolean)
_AllowNone = value
End Set
End Property
Public Property ContextFlag() As String
Get
ContextFlag = _ContextFlag
End Get
Set(ByVal value As String)
_ContextFlag = value
End Set
End Property
Public Sub Add(ByVal Code As String, ByVal Description As String)
If _CodeDescriptions.Count = 0 And AllowNone Then
Me.Items.Add("<None>")
End If
If _CodeDescriptions.Count = 0 And AllowAny Then
Me.Items.Add("<Any>")
End If
Me.Items.Add(Description)
_CodeDescriptions.Add(Code, Description)
If Not _DescriptionCodes.ContainsKey(Description) Then ' suppress duplicates
_DescriptionCodes.Add(Description, Code)
End If
End Sub
Public Property Code() As String
Get
If Me.SelectedItem IsNot Nothing AndAlso Me.SelectedItem.ToString <> "" Then
If _DescriptionCodes.ContainsKey(Me.SelectedItem.ToString) Then
Return (_DescriptionCodes(Me.SelectedItem.ToString))
Else
Return ""
End If
Else
Return ""
End If
End Get
Set(ByVal value As String)
Dim SelectedItem As String = ""
If value <> "" Then
If _CodeDescriptions.TryGetValue(value, SelectedItem) Then
Me.SelectedItem = SelectedItem
Else
Add(value, "Unknown code " & value)
Me.SelectedItem = value
End If
End If
End Set
End Property
Public Sub RemoveElement(ByVal Name As String)
Code = Name
Items.RemoveAt(SelectedIndex)
Dim Description = _CodeDescriptions(Name)
_CodeDescriptions.Remove(Name)
_DescriptionCodes.Remove(Description)
End Sub
End Class
加载组合很容易。
这是一个例子:
ccDefaultFrequencies.Clear()
For Each objFrequency In objVisitFrequencies.Values
With objFrequency
ccDefaultFrequencies.Add(.FrequencyId, .Description)
End With
Next
加载组合后,很容易设置适当的值:
ccDefaultFrequencies.Code = "WEEK"
-并且选择一个选定的值相对简单:
DefaultFrequency = ccDefaultFrequencies.Code
AllowAny和AllowNone允许用户选择“任意”或“无”(但不能同时选择两者,它们是互斥的。两者均返回代码的空字符串。
From: https://bytes.com/topic/net/insights/864850-use-inheritance-produce-really-useful-combo-object