Reputation: 300
Same as the title and using C#. Anyone know how to do this? I have a bunch of data read into a list box but the data doesn't refresh unless I restart the windows form. anyone know how to refresh it on a button click event?
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = (@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\John\Desktop\DB\DB\DB\setup.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
conn.Open();
SqlCommand cmd = new SqlCommand
("SELECT PEOPLE " + "FROM Workers", conn);
try
{
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
listBox1.Items.Add(sdr["people"].ToString());
}
sdr.Close();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
This is in windows form Load. So i'm looking to add a button on my form which refreshes the listbox items list
Upvotes: 1
Views: 1385
Reputation: 12874
Add a Method
private void ShowPeople()
{
// Put your code;
}
and then use the same in your button click
private void Button_Click(object sender,EventArgs e)
{
ShowPeople();
}
Upvotes: 2
Reputation: 19717
To reload data over your sqldatareader (at least I guess you mean set by using the word "refresh") by pressing a button you simply have to access the database again with the same code you are already using. But the important point here is, that you are using a bad design. Therefore I point out an article (30 mins to read) which helped me a lot to improve my code and therefore got rid of code duplication.
Please read: http://imar.spaanjaars.com/416/building-layered-web-applications-with-microsoft-aspnet-20-part-1
After you have read this article I will promise you that you will have a better understanding of how you have to access data in the database within your application
Upvotes: 0