组合框和数据库

时间:2015-12-03 14:45:54

标签: c# database combobox

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

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

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

 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

1 个答案:

答案 0 :(得分:0)

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

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