views:

132

answers:

1

hi

how i can fill collection from database and connect this collection to ComboBox ?

thank's in advance

+2  A: 

The simplest way is to fill a DataTable with your data, and then set it as your ComboBox's DataSource. Here's how to fill a DataTable from SQL Server and use it with a ComboBox named "comboBox1":

using (SqlConnection conn = new SqlConnection("your connection string"))
{
    conn.Open();
    using (SqlCommand cmd = 
        new SqlCommand("SELECT ID, FullName FROM tblPeople", conn))
    {
        using (SqlDataAdapter adap = new SqlDataAdapter(cmd))
        {
            DataTable dt = new DataTable();
            adap.Fill(dt);
            comboBox1.DisplayMember = "FullName";
            comboBox1.ValueMember = "ID";
            comboBox1.DataSource = dt;
        }
    }
}

You'll need to replace "your connection string" with a valid connection string, of course. To see how to build connection strings, check out www.connectionstrings.com.

Now go accept some answers (including this one). :)

MusiGenesis