Reputation: 119
I'm using working in a C# winforms .NET4 application
My goal is to populate a chart control from a specific SQL query.
"SELECT height from person"
simple query but im not sure the best way to get this the query result into the chart control.
Heres what i have so far:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection mainconnection = new SqlConnection("Data Source=commandhq;Initial Catalog=projecttest;Integrated Security=True");
mainconnection.Open();
string query = "SELECT height from persons";
SqlCommand querycommand = new SqlCommand(query, mainconnection);
SqlDataReader querycommandreader = querycommand.ExecuteReader();
Series thesqlresultsplease = new Series();
//Populate series with results from the sql query
chart1.Series[0].XValueMember = thesqlresultsplease.XValueMember; //will this work?
}
My issues are:
How do i get the results from the sqldatareader into the series. If you know of a much better way of going about this please let me know. Im about to start a project so this would be very helpful.
Thanks in advance
Upvotes: 2
Views: 3232
Reputation: 4225
Start with this:
while (querycommandreader.Read())
{
chart1.Series[0].Points.AddY(reader.GetDouble(0));
}
Depending on the Sql Server data type of your "HEIGHT" column, you might have trouble with the GetDouble
part. So if you do, let me know the data type and we'll get it right.
The Read()
method returns a boolean - true
if there are still records being read, false
if you've passed the last on in the set. That's why you can simply use while(querycommandreader.Read())
and in the loop's block do something with each row in the set.
The series' Points
collection has an AddY
method that just takes a double and adds a point to the series. The double we're passing to it comes from column zero of the current record of the reader. That's probably the easiest way to accomplish what you want.
Upvotes: 1
Reputation: 3511
while(querycommandreader.Read())
{
chart1.Series[0].XValueMember = int.Parse(querycommandreader["height"]);
}
Upvotes: 0