在页面加载时填充列表框

时间:2018-02-14 16:12:48

标签: c#

我试图在表单加载时从数据库填充列表框,但是当我加载表单时,没有数据出现。在VS 2017中设置了与数据库的连接,这就是我获得连接字符串的地方。

namespace listbox
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

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

        void fillListBox()
        {
            SqlConnection con = new SqlConnection();
            con.ConnectionString = "Data Source=computername\\SQLEXPRESS;Initial Catalog=footfall;Integrated Security=True";
            con.Open();
            SqlCommand cmd = new SqlCommand("select category from category",con);
            SqlDataReader reader = cmd.ExecuteReader();
            categoryBox.Items.Clear();
            while (reader.Read())
            {
                categoryBox.Items.Add(reader.ToString());
            }
            con.Close();
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您不希望reader.ToString()(返回类型名称),但reader.GetString(0)

while (reader.Read())
{
    categoryBox.Items.Add(reader.GetString(0));
}