我从无法直接查看的表(例如使用SQL Server Management)创建了一个datatable。 我想找到datatable中的列名,应该如何正确地执行此操作?
如何从DataColumn中检索列名:
MyDataTable.Columns(1).ColumnName
获取DataTable中所有DataColumn的名称:
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
参考资料
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);
}
看一下
For Each c as DataColumn in dt.Columns
'... = c.ColumnName
Next
或者:
dt.GetDataTableSchema(...)
' 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
希望这能有所帮助!
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