2015-11-30 31 views
0

我想爲我的Access數據庫中的每個字段填充列表框中的一列。基於Access數據庫中的列動態添加列表框列?

現在我必須手動添加字段:

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

我如何能適應我下面的代碼,每個I運行子時自動添加列?

 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 
+2

列表框對於列是不理想的。 DataGridView將自動添加列併爲您顯示數據 – Plutonix

+0

不錯,它甚至有一個嚮導來引導我。已經建立。太棒了,我想我一直在尋找錯誤的東西。將從現在開始使用datagrid視圖。 – user5480156

回答

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() 

這幫助我用戶熟悉數據庫結構並且可能需要選擇字段名作爲業務邏輯的一部分的項目。例如,允許數據庫知識較少的人在給定字段中對記錄進行標準化。

相關問題