如何将表的列名读入组合框 [英] How do I read the column names of a table into a combobox

查看:73
本文介绍了如何将表的列名读入组合框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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:

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;

推荐答案

查看 DataTable.Columns 财产。这是一个 DataColumnCollection DataColoumn 项目,你想要 DataColumn.ColumnName property。
Look at the DataTable.Columns property. It's a DataColumnCollection of DataColoumn items, and you want the DataColumn.ColumnName property.


尝试此查询

try this query
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N'AcquiredBulkInfo'


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


这篇关于如何将表的列名读入组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆