在过去几天,我一直在努力如何刷新我的图表在C#中。通过数据绑定来更新数据库中的数据。不幸的是,当我将新数据保存到数据库时,图表不会自动执行,我总是必须退出应用程序并重新登录才能更新图表。后续刷新C#图表#
为了解决这个问题,我决定放弃数据绑定,并以编程方式创建我的图表,并在应用程序启动时加载我的图表。然后我创建了一个名为'Refresh'的按钮,用于刷新我的图表。这引发了一个新问题。无论何时点击“刷新”按钮,系统都会保留旧图表并将更新图表添加到“并排”。如果我再次点击,则会显示“并排”图表的3份副本。这继续无限。
下面是我的代码,我附上屏幕截图供您细读。
//this is my constructor
public ChartDemo()
{
InitializeComponent();
connectionString = "Data Source=ADMINISTRATOR;Initial Catalog=AMIS;Persist Security Info=True;User ID=sa;Password=1234";
cnn = new SqlConnection(connectionString);
try
{
cnn.Open();
cnn.Close();
}
catch (Exception)
{
}
//this loads the chart whenever the application is launched
loadChart();
}
private void button1_Click_1(object sender, EventArgs e)
{
//this is used to refersh my chart
loadChart();
}
public void loadChart() {
// this populates my chart with data from the database
SqlConnection cnn = new SqlConnection(connectionString);
SqlCommand sqlcmd = new SqlCommand("SELECT * FROM tbl_salary;", cnn);
SqlDataReader dr;
try
{
cnn.Open();
dr = sqlcmd.ExecuteReader();
while (dr.Read())
{
this.chart1.Series["salaryChart"].Points.AddXY(dr.GetString(1), dr.GetInt32(2));
}
cnn.Close();
}
catch (Exception)
{
}
}
如果你想自动更新,那么你可以使用线程 – 2014-11-23 05:35:48
太好了!有用!非常感谢。 – myelow 2014-11-23 06:37:52