简体   繁体   中英

How do I load a Windows Forms Combobox, with MSSQL Database data in Visual Studio?

I've been trying different methods of adding MSSQL data to a Windows Forms Combobox for quite some time and have been unable to get it to work. I must be missing something, but I can't figure out what it might be.

I am trying to add the Description data form a table named Course, in my SQL Database named StudentDatabase.

I am using Microsoft SQL Management Studio 2018, and Visual Studio 2017.

namespace WindowsFormsApp3
{
    public partial class Form1 : Form
    {


        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            FillCombobox();
        }

        void FillCombobox()
        {
            string sql = "SELECT * FROM Course";

            SqlConnection dbConn = new SqlConnection("Data Source = localhost; Initial Catalog = StudentDatabase; Integrated Security = SSPI");
            SqlCommand dbComm = new SqlCommand(sql, dbConn);
            SqlDataReader myReader;

            try
            {
                dbConn.Open();
                myReader = dbComm.ExecuteReader();

                while (myReader.Read())
                {
                    string Desc = myReader["Description"].ToString();
                    comboBox1.Items.Add(Desc);
                }

            }
            catch(Exception ex)
            {
                MessageBox.Show("Error");
            }
        }

    }

}

I expect the Combox box to fill with the different Course Descriptions, yet it remains empty and I receive no error message.

Try to make a full list of the items first, then bind them to the ComboBox.

List<string> _descriptions;

//Fill the list from the database
string query = "SELECT Description FROM Course";
    using(SqlCommand dbComm= new SqlCommand(query, dbConn))
    {
        using (SqlDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
            _descriptions.Add(reader.GetString(0));
            }         
        }
    }

//Add items to the ComboBox
foreach (string str in _descriptions)
{
    comboBox1.Items.Add(str);
}

//Or add with a datasource without re-iterating
comboBox1.Datasource = _descriptions;

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