Click here to Skip to main content
15,884,177 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
I have a question. I need to have the rows of a table displayed as the list-elements of a combobox Actually I have a table called 'Table1' with two columns *Id* and *Name* and i need to have a combobox that once the form loads can read these column names as the elements of the combobox so if a search needs to be performed on the table, a choice can be done as per what column value. But when the form loads the combobox is empty

Please find my code below:


What I have tried:

C#
string sd = @"select * from AcquiredBulkInfo";
            SqlConnection con = new SqlConnection(MyConnectionString);
            SqlCommand cmd = new SqlCommand(sd, con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            comboBox1.DataSource = dt;
Posted
Updated 16-Nov-16 7:31am

Look at the DataTable.Columns property. It's a DataColumnCollection of DataColoumn items, and you want the DataColumn.ColumnName property.
 
Share this answer
 
v2
try this query
SQL
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N'AcquiredBulkInfo'
 
Share this answer
 
v2
Comments
#realJSOP 9-Nov-16 8:59am    
Why hit the database again? He has all the info he needs in the datatable object.
Nganku Junior 9-Nov-16 12:20pm    
@John Simmons : The purpose behind my 'gymnastics' is so I can enforce search criterion based on column name
Karthik_Mahalingam 9-Nov-16 23:17pm    
he just need to bind the column names in the combobox, so there is no point of bringing the entire data to the application just for showing the column names.
Nganku Junior 11-Nov-16 3:09am    
Hey when I use this code:
SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N'AcquiredBulkInfo'
The datagridview displays ;
System.Data.DataRowView
What is lacking please
Karthik_Mahalingam 11-Nov-16 4:06am    
datagridview or combobox?
C#
void Search_Crit()
           {
           string sd = @"SELECT COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME= 'AcquiredBulkInfo'";
           SqlConnection con = new SqlConnection("connection string");
           con.Open();
           SqlCommand cmd = new SqlCommand(sd, con);
           SqlDataReader dr;
           dr = cmd.ExecuteReader();
           if (dr.HasRows)
               {
               while (dr.Read())
                   {
                   comboBox1.Items.Add(dr[0].ToString());
                   }
               }
           dr.Close();
           con.Close();
           }
 
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