所以我从一个表中创建一个数据表,我无法直接查看(即使用sql server管理)。我想找到数据表中的列名,这样做的正确方法是什么?
答案 0 :(得分:19)
这是从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
<强>参考强>
答案 1 :(得分:3)
您可以循环遍历数据表的列集合。
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);
}
希望这有帮助!
答案 2 :(得分:1)
看看
For Each c as DataColumn in dt.Columns
'... = c.ColumnName
Next
或:
dt.GetDataTableSchema(...)
答案 3 :(得分:0)
您是否可以访问您的数据库,如果是这样,只需打开它并查找该列并使用SQL调用来检索所需的数据。
表单上的一个简短示例,用于从数据库表中检索数据:
表单只包含名为DataGrid的GataGridView
数据库名称:DB.mdf
表名:DBtable
表中的列名:名称为varchar(50),Age为int,Gender为bit。
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调用:&#34; SELECT Name FROM DBtable&#34;这样,DataGridView将只显示列名。
我只是一个新手,但我强烈建议摆脱这些自动生成向导。使用SQL,您可以完全访问您的数据库以及会发生什么 最后一件事,如果您的数据库没有使用SQLClient,只需将其更改为OleDB即可。
示例:&#34; Dim conn As New SqlClient.SqlConnection
&#34;成为:Dim conn As New OleDb.OleDbConnection
答案 4 :(得分: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
希望这可以提供帮助!