根据Access数据库中的列动态添加列表框列?

时间:2015-11-30 18:33:11

标签: sql vb.net listbox ms-access-2010

我想在我的列表框中为我的Access数据库中的每个字段填充一列。

现在我必须手动添加字段:

QUERBOX.Columns.Add("Requestor Name", 200, HorizontalAlignment.Left)

我如何调整下面的代码,以便在每次运行sub时自动添加列?

      Dim queryString As String = "SELECT * FROM Table1;"





    Dim connection As OleDbConnection
    Dim command As OleDbCommand
    Dim data_reader As OleDbDataReader








querbox.clear


    connection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\apt.accdb")
    connection.Open()


    command = New OleDbCommand(queryString, connection)
    data_reader = Command.ExecuteReader



    If data_reader.HasRows Then
        While data_reader.Read
            Dim newitem As New ListViewItem()
            newitem.Text = data_reader.GetValue(0) 'first column
            newitem.SubItems.Add(data_reader.GetValue(1)) 'second column
            QUERBOX.Items.Add(newitem)

        End While
    End If

1 个答案:

答案 0 :(得分:0)

正如Plutonix在评论中所建议的那样,DataGridView可能最适合,但为了回答这里的问题我是如何做类似的事情:

connection.Open()
'' Fill a DataTable with all of the Column schema for the given table of 'Table1'
Dim schemaTable As DataTable = connection.GetSchema("Columns", New String() {Nothing, Nothing, "Table1", Nothing})
'' Iterate through each column in the Schema Table
For i = 0 To schemaTable.Rows.Count - 1 Step 1
    '' Declare a new item for the list
    Dim newItem As New ListViewItem()
    newItem.Text = schemaTable.Rows(i)!COLUMN_NAME.ToString()
    newItem.SubItems.Add(schemaTable.Rows(i)!COLUMN_NAME.ToString()
    '' Add new item to the interface
    QUERBOX.Items.Add(newItem)
Next
connection.Close()

这帮助我完成了用户熟悉数据库结构的项目,并且可能需要选择fieldname作为业务逻辑的一部分。例如,允许具有少量数据库知识的人标准化给定字段中的记录。