2011-07-22 353 views

回答

18

這是如何從一個DataColumn檢索列名:

MyDataTable.Columns(1).ColumnName 

要在數據表中得到所有DataColumns的名字:

Dim name(DT.Columns.Count) As String 
Dim i As Integer = 0 
For Each column As DataColumn In DT.Columns 
    name(i) = column.ColumnName 
    i += 1 
Next 

參考

+0

昏暗名作爲字符串()=新字符串(){} 爲每列作爲DataColumn的在testTable.Columns 名= column.ColumnName 接着 它不會由於IM添加串變暗喜歡這個名稱作爲字符串()=新的字符串(){} 對於作爲每列的DataColumn在testTable.Columns 名= column.ColumnName 接下來 我試圖將字符串添加到字符串數組,我是什麼樂隊這裏錯了嗎? –

+0

已更新我的代碼示例以實現我相信您之後的操作。 –

1

For Each c as DataColumn in dt.Columns 
    '... = c.ColumnName 
Next 

或:

dt.GetDataTableSchema(...)

2

你可以通過列集DataTable的環。

VB

Dim dt As New DataTable() 
For Each column As DataColumn In dt.Columns 
    Console.WriteLine(column.ColumnName) 
Next 

C#

DataTable dt = new DataTable(); 
foreach (DataColumn column in dt.Columns) 
{ 
Console.WriteLine(column.ColumnName); 
} 

希望這有助於!

0

您是否有權訪問數據庫?如果是這樣,只需打開它並查找列並使用SQL調用來檢索所需的數據庫。

形式從數據庫表中檢索數據上的一個簡單的例子:

表格只包含一個名爲GataGridView DataGrid的

數據庫名稱:DB.mdf

表名:DBTABLE

表中的列名稱:名稱爲varchar(50),Age爲int,性別爲位。

Private Sub DatabaseTest_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load 
    Public ConString As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\{username}\documents\visual studio 2010\Projects\Userapplication prototype v1.0\Userapplication prototype v1.0\Database\DB.mdf;" & "Integrated Security=True;User Instance=True" 
    Dim conn As New SqlClient.SqlConnection 
    Dim cmd As New SqlClient.SqlCommand 
    Dim da As New SqlClient.SqlDataAdapter 
    Dim dt As New DataTable 
    Dim sSQL As String = String.Empty 
    Try 
     conn = New SqlClient.SqlConnection(ConString) 
     conn.Open() 'connects to the database 
     cmd.Connection = conn 
     cmd.CommandType = CommandType.Text 
     sSQL = "SELECT * FROM DBtable" 'Sql to be executed 
     cmd.CommandText = sSQL 'makes the string a command 
     da.SelectCommand = cmd 'puts the command into the sqlDataAdapter 
     da.Fill(dt) 'populates the dataTable by performing the command above 
     Me.DataGrid.DataSource = dt 'Updates the grid using the populated dataTable 

     'the following is only if any errors happen: 
     If dt.Rows.Count = 0 Then 
      MsgBox("No record found!") 
     End If 
    Catch ex As Exception 
     MsgBox(ErrorToString) 
    Finally 
     conn.Close() 'closes the connection again so it can be accessed by other users or programs 
    End Try 
End Sub 

這將從數據庫表中提取所有行和列以供查看。
如果您只想獲取名稱,只需使用以下方法更改sql調用:「SELECT Name FROM DBtable」這種方式DataGridView將只顯示列名稱。

我只是一個菜鳥,但我強烈建議擺脫這些自動生成奇才。使用SQL,您可以完全訪問數據庫,並且會發生什麼情況。
還有一件最後一件事,如果您的數據庫不使用SQLClient,只需將其更改爲OleDB。

例: 「Dim conn As New SqlClient.SqlConnection」 變爲:Dim conn As New OleDb.OleDbConnection

0
' i modify the code for Datatable 

For Each c as DataColumn in dt.Columns 
For j=0 To _dataTable.Columns.Count-1 
      xlWorksheet.Cells (i+1, j+1) = _dataTable.Columns(j).ColumnName 
Next 
Next 

希望這可以幫助!

相關問題