我正在编写一个 VB.NET WindowsForms 应用程序,我想通过设置其 DataSource 属性来从 SQLite 数据库表填充 ComboBox 控件。这应该有效:
但是当我运行代码时,ComboBox 中填充了空字符串:
Dim sqliteCon As New SQLiteConnection
sqliteCon.ConnectionString = "Data Source=" + dbFileName
sqliteCon.Open()
Dim sqliteCmd As SQLiteCommand = sqliteCon.CreateCommand()
Dim reader As SQLiteDataReader
'-----------------------------------
sqliteCmd.CommandText = "CREATE TABLE IF NOT EXISTS colorsT (colorID INTEGER PRIMARY KEY, Color TEXT);"
sqliteCmd.ExecuteNonQuery()
'-----------------------------------
sqliteCmd.CommandText = "INSERT INTO colorsT (Color) VALUES ('Red'), ('Green'), ('Blue');"
sqliteCmd.ExecuteNonQuery()
'-----------------------------------
sqliteCmd.CommandText = "SELECT Color FROM colorsT ORDER BY Color;"
reader = sqliteCmd.ExecuteReader()
Dim dT As New DataTable
dT.Load(reader)
ComboBox1.DataSource = dT
ComboBox1.DisplayMember = "Color"
Log(ComboBox1.Items(1).ToString) 'outputs: System.Data.DataRowView
dT.Dispose()
reader.Close()
sqliteCmd.Dispose()
sqliteCon.Close()
我仍然可以通过使用循环使用正确的值填充 ComboBox:
For Each row As DataRow In dT.Rows
ComboBox1.Items.Add(row(0).ToString)
Next
但我认为这是一种效率较低的方法。 这里可能出现什么问题?
在 DataSource 之前设置 DisplayMember