[英]Populating listbox on page load
Im attempting to populate a listbox from a database on form load, but when i load the form no data appears. 我试图在表单加载时从数据库填充列表框,但是当我加载表单时,没有数据出现。 The connection to the database is setup in VS 2017 and thats where I got the connection string.
与数据库的连接是在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();
}
}
}
You don't want reader.ToString()
(which returns the type name) but reader.GetString(0)
: 您不想要
reader.ToString()
(返回类型名称),但需要reader.GetString(0)
:
while (reader.Read())
{
categoryBox.Items.Add(reader.GetString(0));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.