所以我有一个组合框,其中包含来自MySql数据库的表名,它们在表单加载时使用show tables
查询自动列出。
无论如何在组合框中显示其他内容但文本值仍然是原始表名吗?
答案 0 :(得分:1)
这不是不可能的。这是一个简单的例子:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' This would be whatever you are pulling from the database. For the purpose of this example, it is just mock data.
Dim dataFromDatabase As IEnumerable(Of String) = {"1st table from db", "2nd table from db", "etc."}
' What you actually want to display in the combobox. It should be in the same order as above and have the same number of items. Items must be unique.
Dim valuesToDisplayInComboBox As IEnumerable(Of String) = {"1st item", "2nd item", "3rd item"}
' This is what ties the two together. You would probably want this to be larger in scope than this example.
Dim dataCollection As New Dictionary(Of String, String)
For i As Integer = 0 To dataFromDatabase.Count - 1 Step 1
dataCollection.Add(valuesToDisplayInComboBox(i), dataFromDatabase(i))
Next
ComboBox1.DataSource = valuesToDisplayInComboBox
End Sub
End Class
现在你有一个Dictionary
将2连在一起,所以每当用户选择组合框中的某些内容时,你会转到Dictionary
并查找相应的表名。
答案 1 :(得分:1)
Class Element
Public ItemName as String = ""
Public ItemData As Object = Nothing
' Object allows it to be reusable beyond this use
Public Sub New(iName as String, iData As Object)
ItemName = iName
ItemData = iData
End Sub
Public overrides Function ToString As String
Return ItemName
End sub
End Class
....
For each s as string in listoftablesfromdatabase
' dont know how you are getting your list,
' but here is one way to alias them
Dim El as Element
Select Case s
Case "tbl_event_birthdays_september"
El = New Element("September Birthdays", s)
case ...
case ...
End Select
ComboBox1.Items.Add(el)
Next s
该课程将自动使用您提供的友好名称。获取真正选择的项目名称:
realName = ComboBox1.SelectedItem.ItemData.Tostring
可能不需要.ToString这与Douglas Barbin的想法没什么不同,它仍然关联2个字符串,它只是不使用字典。或者,您可以将元素存储在List(元素)或Dictionary中,并将其绑定到数据源,如Douglas所示。
如果用户一遍又一遍地回到Combo,那么请使用List或Dictionary,但不是临时的 - 构建一次并反复使用它。