组合框和数据库

本文关键字:数据库 组合 | 更新日期: 2023-09-27 18:25:27

我想在组合框中显示数据库中项目的数据。我用了这个代码:

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

我用了这个代码,但没用。我创建了一个名为Connect`class的类。这是代码:

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

你能给我举个例子吗Thx

组合框和数据库

您必须在设计器或代码中将列值分配给组合框。在组合框的属性中,将itemNames放在DisplayMember和ValueMember中,或者在如下代码中执行:

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