如何在组合框中显示我的表(数据库)的列名

时间:2018-12-28 09:35:39

标签: c# sql .net sql-server winforms

如何在组合框中显示我的表(数据库)的列名?

1 个答案:

答案 0 :(得分:3)

您可以尝试以下方法将列名绑定到组合框中。在这里,我使用INFORMATION_SCHEMA.COLUMNS来获取列名。

public Form1()
        {
            InitializeComponent();
            BindColumnnameToComboBox();
        }
        public void BindColumnnameToComboBox()   
        {
            DataRow dr;


            SqlConnection con = new SqlConnection(@"Data Source=NiluNilesh;Initial Catalog=mynewdata;Integrated Security=True");
            con.Open();
            SqlCommand cmd = new SqlCommand("select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS i where i.TABLE_NAME = 'Mark'", con);
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            sda.Fill(dt);

            dr = dt.NewRow();
            dr.ItemArray = new object[] { 0, "--Select--" };
            dt.Rows.InsertAt(dr, 0);

            comboBox1.ValueMember = "COLUMN_NAME";

            comboBox1.DisplayMember = "COLUMN_NAME";
            comboBox1.DataSource = dt;

            con.Close();


        }