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.
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)
:
while (reader.Read())
{
categoryBox.Items.Add(reader.GetString(0));
}
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.