Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi everyone!

I am trying to retrieve a list of columns in a particular table in the database. Here is what I have so far:

var dtCols = conn.GetSchema("Columns", new[] { "waveform_db", null, "Electrical" });

Is this a proper way? If so, how can I access this list to add to a combobox? Here is what I have so far.

C#
if (dtCols != null)
                    {
                        foreach (var dr in dtCols)
                        {
                            // code to add to combobox
                        }
                    }


The compiler is balking at the beginning of the foreach statement.
"foreach statement cannot operate on variables of type "system.data.datatable" because "system.data.datatable" does not contain a public definition for "getenumerator".

I'm not real sure what this means. Does anyone have any hints as to how to resolve this issue?

Thanks everyone!
Posted

You could do it like this:
VB
Try
    Dim SQLConnection As SqlConnection = New SqlConnection()
    SQLConnection.ConnectionString = DBconnectionWork
    Dim SQLCommand As SqlCommand = SQLConnection.CreateCommand()
    SQLCommand.CommandText = "select c.name from syscolumns c (nolock), sysobjects o (nolock) " + _
                             "where c.id = o.id and o.name = 'tablename' " + _
                             "  and c.name <> 'timestamp' " + _
                             "order by colid"
    SQLConnection.Open()
    Dim myReader As SqlDataReader = SQLCommand.ExecuteReader()
    Do While myReader.Read()
        ComboBox1.Items.Add(myReader.GetString(0))
    Loop
    myReader.Close()
    SQLConnection.Close()
Catch ex As Exception
    MsgBox(ex.ToString, MsgBoxStyle.Critical)
End Try
 
Share this answer
 
v2
Comments
joshrduncan2012 21-Jan-13 14:41pm    
That command doesn't work for SQL Server. syscolumns is not recognized.
Wietze Bron 21-Jan-13 14:52pm    
Ofcourse it works. The SQL query is correct.
For 'tablename' you have to substitute your own table.
For DBconnectionWork you have to substitute your own connection string.
C#
foreach (DataRow dr in dtCols.Rows)


Your specific error is because you need to iterate the Rows of the DataTable not the DataTable itself.

However:
Wietze Bron is correct, his method is exactly what you need.
 
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