Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am trying to find the number of columns in my table: Table1.

How do I do that?

VB
Dim connStr, cmdStr As String
Try
    connStr="connection string works"
    cmdStr = "SELECT * FROM [Table1];"
    Using conn As New SqlConnection(connStr)
         Using cmd As New SqlCommand(cmdStr, conn)
              conn.Open()
              Using myreader = cmd.ExecuteReader()
                   If myreader.Read() Then
                         For Each k In columns
                               'How do you find # of columns
                         Next
                   End If
               End Using
               conn.Close()
               cmd.Dispose()
               conn.Dispose()
          End Using
     End Using
Catch ex As Exception
     TextBox6.Text = "Username: " & ex.ToString()
End Try
Posted
Comments
[no name] 16-Aug-14 12:04pm    
Did you look at the documentation? http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader(v=vs.110).aspx
Ashi0891 16-Aug-14 13:01pm    
you can increment a variable in for each loop.

Hello Friend...Try This

SELECT Count(*) FROM INFORMATION_SCHEMA.Columns where TABLE_NAME = 'YourTableName'

Thanks
 
Share this answer
 
Comments
Oshtri Deka 19-Aug-14 17:23pm    
My 5.
You can use FieldCount property[^].
Here is an example - Get number of columns in SqlDataReader[^].
 
Share this answer
 
try this..

SELECT COUNT(COLUMN_NAME) FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME = 'TableName'
 
Share this answer
 
you can use this query to get no of columns
cmd.CommandText = "SELECT count(*) FROM [Table1];";
Int32 count = (Int32) cmd.ExecuteScalar();
 
Share this answer
 
v2
Comments
CHill60 18-Aug-14 5:19am    
That counts rows, not columns
Oshtri Deka 19-Aug-14 17:22pm    
Wrong!
Hi,

Check this...

How to : Count Columns in a table?[^]


Hope this will help you.


Cheers
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900