Get table column names in combo box

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

+2


a source to share


4 answers


The correct way to do this on SQL Server 2005 and up (you haven't specified clearly enough which version you are using) would be checking the system catalog views that live in the schema sys

:

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

      



The catalog view sys.columns

contains fairly detailed information about the columns of a table - the table is identified by a column object_id

that is the internal identifier for the given table.

+1


a source


This will give you a list of tables

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

      



And this should contain information about the columns in the table

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

      

+1


a source


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

Regarding getting items in a combobox, you can find volumes of information about it on msdn at this link http://msdn.microsoft.com/en-us/library/aa983551(VS.71).aspx

Enjoy!

0


a source


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();

      

0


a source







All Articles