简体   繁体   中英

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. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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