Click here to Skip to main content
15,921,174 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to display all the columns column names except the PRIMARY KEY in a listbox in C#. How do I do that?

My code gives me the following error:
Invalid column name 'column_type'.

Please Help. I am using MS-SQL for the same.

What I have tried:

C#
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
       {

               string cmdstr = @"select * from information_schema.columns where table_name = '" + comboBox1.SelectedItem + "' and column_type <> 'PRI'";
               string conStr = @"Data Source=INPDDBA027\NGEP;Initial Catalog=Dev_Server;Integrated Security=True";
               DataTable dt = new DataTable();
               SqlDataAdapter sda = new SqlDataAdapter(cmdstr, conStr);
               sda.Fill(dt);
               listBox2.DataSource = dt;
               listBox2.DisplayMember = "Column_Name";
       }
Posted
Updated 27-Jul-16 4:05am
Comments

try this

SQL
select COLUMN_NAME from information_schema.columns where table_name = 'YourTableName' 
except 
SELECT COLUMN_NAME
    FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
        JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu ON tc.CONSTRAINT_NAME = ccu.Constraint_name
    WHERE tc.CONSTRAINT_TYPE = 'Primary Key' and  tc.table_name  = 'YourTableName'  


Note: Your code is Vulnerable to SQL injection [^] attacks
Always use Parameterized queries to prevent SQL Injection Attacks in SQL Server[^]
 
Share this answer
 
Column_Type is not a valid field in the table you are accessing in SQL

Try
SQL
SELECT *
    FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
        JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu ON tc.CONSTRAINT_NAME = ccu.Constraint_name
    WHERE tc.CONSTRAINT_TYPE = 'Primary Key'
to get which columns that are primary keys and join to the table you are referring to.
 
Share this answer
 
v3

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