问题遇到的现象和发生背景
我打算为C#,chart控件绑定数据
private void TmainForm_Load(object sender, EventArgs e)
{
string strconn;
//初始化连接字符串
strconn = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;Connect Timeout=30";
string strSQL; //查询命令
DataSet ds1 = new DataSet(); //数据集ds1
//strSQL = "select * from Grade where Sname =N'" + textBox1.Text + "'";
strSQL = "select ranking,Time1 from Grade ";
SqlConnection conn = new SqlConnection(strconn); //连接对象
conn.Open();
SqlDataAdapter myDa = new SqlDataAdapter(strSQL, conn); //数据接合器(适配器)
SqlCommand comm = new SqlCommand(); //查询命令
comm.Connection = conn;
comm.CommandText = strSQL;
comm.CommandType = CommandType.Text;
SqlDataReader dr;
dr = comm.ExecuteReader();
dataGridView1.DataSource = dr;
try
{
conn.Open();
myDa.Fill(ds1, "ranking");
Series dataTable3Series = new Series("dataTable3"); //dataTable3为数据源
dataTable3Series.Points.DataBind(dr, "Time1", "ranking", "");
dataTable3Series.XValueType = ChartValueType.DateTime; //设置X轴类型为时间
dataTable3Series.ChartType = SeriesChartType.Line; //设置Y轴为折线
chart1.Series.Add(dataTable3Series); //加入 chart1 ** 此处为数据绑定处**
myDa.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "操作数据库出错!",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
this.Tag = false;
}
finally
{
conn.Close(); // 关闭数据库连接
}
dr.Close();//关闭读取器连接
}