[.net] In vb.net, how to get the column names from a datatable

So i create a datatable from a table i can't directly view(i.e. using sql server management). I want to find the column names that are in the datatable, what would be the correct way do this?

This question is related to .net vb.net datatable

The answer is


You can loop through the columns collection of the 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);
}

Hope this helps!


Look at

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

or:

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

Hope this could be help!


Do you have access to your database, if so just open it up and look up the column and use an SQL call to retrieve the needed.

A short example on a form to retrieve data from a database table:

Form contain only a GataGridView named DataGrid

Database name: DB.mdf

Table name: DBtable

Column names in table: Name as varchar(50), Age as int, Gender as 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

This will fetch all the rows and columns from your database table for review.
If you want to only fetch the names just change the sql call with: "SELECT Name FROM DBtable" this way the DataGridView will only show the column names.

I'm only a rookie but i would strongly advise to get rid of theses auto generate wizards. Using SQL you have full access to your database and what happens.
Also one last thing, if your database doesn't use SQLClient just change it to OleDB.

Example: "Dim conn As New SqlClient.SqlConnection" becomes: Dim conn As New OleDb.OleDbConnection


Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to vb.net

How to get parameter value for date/time column from empty MaskedTextBox HTTP 415 unsupported media type error when calling Web API 2 endpoint variable is not declared it may be inaccessible due to its protection level Differences Between vbLf, vbCrLf & vbCr Constants Simple working Example of json.net in VB.net How to open up a form from another form in VB.NET? Delete a row in DataGridView Control in VB.NET How to get cell value from DataGridView in VB.Net? Set default format of datetimepicker as dd-MM-yyyy How to configure SMTP settings in web.config

Examples related to datatable

Can't bind to 'dataSource' since it isn't a known property of 'table' How to get a specific column value from a DataTable in c# Change Row background color based on cell value DataTable How to bind DataTable to Datagrid Find row in datatable with specific id Datatable to html Table How to Edit a row in the datatable How do I use SELECT GROUP BY in DataTable.Select(Expression)? How to fill a datatable with List<T> SqlBulkCopy - The given value of type String from the data source cannot be converted to type money of the specified target column