簡體   English   中英

如何在Visual Studio中使用MSSQL數據庫數據加載Windows窗體組合框?

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

我一直在嘗試將MSSQL數據添加到Windows Forms Combobox的不同方法,但是已經無法正常工作了。 我一定想念一些東西,但我不知道可能是什么。

我試圖在名為StudentDatabase的SQL數據庫中,從名為Course的表中添加Description數據。

我正在使用Microsoft SQL Management Studio 2018和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");
            }
        }

    }

}

我希望“ Combox”框充滿不同的“課程說明”,但它仍然為空,並且沒有收到任何錯誤消息。

嘗試首先列出所有項目,然后將它們綁定到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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM