简体   繁体   English

组合框和数据库

[英]Combo Box and Database

I want to show data in my Combo box from items in Database. 我想在“组合”框中显示数据库中的项目中的数据。 I used this code: 我使用以下代码:

Connect con = new Connect(); 
combox1.DataSource = con.executeSelect("SELECT itemNames FROM MsBook");

I used this code, but it didnt work. 我使用了这段代码,但是没有用。 I made a class with its name is Connect` class. 我做了一个名为Connect`的类。 Here is the code: 这是代码:

 class Connect
{
    SqlConnection con;
    public Connect()
    {
        String connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=" + Application.StartupPath + @"\Database1.mdf;Integrated Security=True;User Instance=True";
        con = new SqlConnection(connectionString);
    }

    public DataTable executeSelect(String query)
    {
        con.Open();
        SqlDataAdapter adapter = new SqlDataAdapter(query, con);
        DataTable dt = new DataTable();
        adapter.Fill(dt);
        con.Close();

        return dt;
    }

    public void execute(String query)
    {

        con.Open();
        SqlCommand cmd = new SqlCommand(query, con);
        cmd.ExecuteNonQuery();

        con.Close();
    }
}

Could you please give me example to this matter Thx 你能给我举个例子吗?

You have to assign the column values to the combobox in either the designer or code. 您必须在设计器或代码中将列值分配给组合框。 In the properties of the ComboBox put itemNames in the DisplayMember and ValueMember or do it in code like the following: 在ComboBox的属性中,将itemNames放在DisplayMember和ValueMember中,或者在类似于以下代码中进行操作:

Connect con = new Connect(); 
combox1.DisplayMember = "itemNames";
combox1.ValueMember = "itemNames";
combox1.DataSource = con.executeSelect("SELECT itemNames FROM MsBook");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM