2011-07-22 355 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 

希望这可以帮助!

相关问题