saeed
saeed

Reputation: 673

Retrieve column names of a table into a combo box

Im using c# windows form application. I have a database with many tables. Each table has several columns. I need to populate the combo box with the column names for a selected table.

Upvotes: 2

Views: 3288

Answers (4)

Maria Sheikh
Maria Sheikh

Reputation: 87

You can use this code

string  sqlquery="select column_name FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME = 'student' ORDER BY ORDINAL_POSITION";
     DataFind.Open();
     cmd = new SqlCommand(sqlquery, DataFind);

     SqlDataReader DR = cmd.ExecuteReader();

       while (DR.Read())
     {
         comboBox1.Items.Add(DR[0]);

     }
     DataFind.Close();

Upvotes: 0

marc_s
marc_s

Reputation: 755157

The proper way of doing this on SQL Server 2005 and up (you didn't specify quite clearly what version you're using) would be to inspect the system catalog view, which live in the sys schema:

SELECT 
    name
FROM    
    sys.columns
WHERE
    object_id = object_id('YourTableNameHere')
ORDER BY
    name    

The sys.columns catalog view gives you quite a bit of information about the columns for a table - the table is identified by the object_id column, which is the internal ID for that table in question.

Upvotes: 1

Doug
Doug

Reputation: 5328

Here is how you can query the column names from sql server. Other databases are similar to this. http://blog.sqlauthority.com/2008/08/05/sql-server-2005-get-field-name-and-type-of-database-table/

As far as getting the items into a combobox you can find volumes of information on this on msdn at this link http://msdn.microsoft.com/en-us/library/aa983551(VS.71).aspx

Enjoy!

Upvotes: 0

Adriaan Stander
Adriaan Stander

Reputation: 166486

This should give you the list of tables

SELECT name 
FROM dbo.sysobjects 
WHERE xtype = 'U' 

And this should give you column information per table

select * 
from INFORMATION_SCHEMA.COLUMNS 
where TABLE_NAME = 'yourTable'

Upvotes: 1

Related Questions