I want to display all the columns column names except the PRIMARY KEY in a listbox in C#. How do I do that?
The code that I have tried till now is:
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";
}
The above code gives me the following error:
Invalid column name 'column_type'.
Please Help. I am using MS-SQL for the same.
Try this query to get Columns other than Primary Key ( Not tested thoroughly please test before using )
SELECT C.ORDINAL_POSITION, C.TABLE_NAME , C.COLUMN_NAME from
INFORMATION_SCHEMA.COLUMNS C LEFT OUTER JOIN
( INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col INNER JOIN
INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab ON Col.Constraint_Name = Tab.Constraint_Name
AND Col.Table_Name = Tab.Table_Name
) ON C.COLUMN_NAME = Col.COLUMN_NAME AND Constraint_Type = 'PRIMARY KEY'
WHERE Tab.CONSTRAINT_NAME IS NULL
AND C.TABLE_NAME = 'YOUR_TABLE_NAME' -- Table name goes here
AND C.TABLE_SCHEMA = 'dbo' -- Change this to your schema if your table resides on a different schema
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.