【发布时间】:2011-10-11 03:17:47
【问题描述】:
所以我从无法直接查看的表中创建数据表(即使用 sql 服务器管理)。我想查找数据表中的列名,这样做的正确方法是什么?
【问题讨论】:
所以我从无法直接查看的表中创建数据表(即使用 sql 服务器管理)。我想查找数据表中的列名,这样做的正确方法是什么?
【问题讨论】:
这是从 DataColumn 中检索列名的方法:
MyDataTable.Columns(1).ColumnName
要获取 DataTable 中所有 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
参考文献
【讨论】:
您可以遍历数据表的列集合。
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);
}
希望这会有所帮助!
【讨论】:
看看
For Each c as DataColumn in dt.Columns
'... = c.ColumnName
Next
或:
dt.GetDataTableSchema(...)
【讨论】:
您是否可以访问您的数据库,如果可以,只需打开它并查找列并使用 SQL 调用来检索所需的内容。
从数据库表中检索数据的表单上的一个简短示例:
表单只包含一个名为 DataGrid 的 GataGridView
数据库名称:DB.mdf
表名:DBtable
表中的列名:名称为 varchar(50),年龄为 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
【讨论】:
' 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
希望这能有所帮助!
【讨论】: