我有一个访问数据库,其中包含此格式Type1;Type2;Type3
的单元格
我想将这些值带入组合框中,因此组合框集合看起来像这样:
Type1
Type2
Type3
我知道在这里得到的值是我的代码:
'type_text is the name of the combobox
Dim ds As New DataSet()
Dim ConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\equip_full.mdb;Jet OLEDB:Database Password="
Dim db As String = "SELECT Type FROM EquipmentType Where Equipment= '" & item_text.Text & "'"
Using cn As New OleDbConnection(ConnectionString)
Using da As New OleDbDataAdapter(db, cn)
da.Fill(ds, "Type")
End Using
End Using
With type_text
.DisplayMember = "Type"
.DataSource = ds.Tables("Type")
End With
我也知道如何分隔字符串
Dim s As String = type_text.Text
Dim parts As String() = s.Split(New Char() {";"c})
Dim part As String
For Each part In parts
Me.type_text.Items.Add(part)
Next
如何组合这两个部分?
答案 0 :(得分:1)
使用OleDbDataReader而不是填充DataSet
Dim ConnectionString As String = "......."
Dim db As String = "SELECT [Type] FROM EquipmentType Where Equipment= @item"
Using cn As New OleDbConnection(ConnectionString)
Using cmd = new OleDbCommand(db, cn)
cn.Open()
cmd.Parameters.Add("@item", OleDbType.VarWChar).Value = item_text.Text
Using reader = cmd.ExecuteReader()
while reader.Read()
Dim parts As String() = reader(0).ToString().Split(New Char() {";"c})
For Each part In parts
Me.type_text.Items.Add(part)
Next
End While
End Using
End Using
End Using
另请注意,我在名为Type的字段周围放了方括号。我很确定这是一个保留关键字,因此您不能在查询文本中使用它,但需要括号来帮助引擎将其识别为字段名称。如果仍有可能,最好更改该字段名称。
我在代码中更改的另一件事是构建命令文本的字符串连接。这在Access中也是一种不好的做法,其中Sql Injection更难一些。在任何情况下,如上所述使用参数化查询有助于保持命令清晰易懂,而无需提及由于文本值周围缺少引号而导致的错误