Reputation:
I've done some research and I've managed to found information about drawing a graph where you hard code a Data Table with fixed values.
This is the link: How to create chart using data table
My problem is however;
I don't have a Data Table like that. I have DataAccess class that call the data from a database then stores it in a Data Table;
public DataTable select_top_sheep(string farmerid)
{
dt = new DataTable();
try
{
conn.Open();
SqlCommand cmd =
new SqlCommand("SELECT TOP 10
S.SheepID
,W.Weight
FROM[Farmstat_V1.0].[dbo].[Sheep] S
INNER JOIN[Farmstat_V1.0].[dbo].[Weight] W
ON S.SheepID = W.SheepID
WHERE S.FarmerID = '" + farmerid + "'
ORDER BY W.Weight DESC", conn);
SqlDataReader reader = cmd.ExecuteReader();
dt.Load(reader);
}
catch (Exception)
{
throw;
}
finally
{
conn.Close();
}
return dt;
}
Then on my form I call this method to get the data, but how can I from here display it in a graph? I can see that the data stores successfully in the DataTable when I run the program in debug mode.
I just want to use the basic Chart tool from the toolbox to display the data graphically.
Upvotes: 0
Views: 4003
Reputation:
I have managed to figure out the answer with the use of the link I provided in my question.
This is what I did;
protected void Page_Load(object sender, EventArgs e)
{
// Initializes a new instance of the DataAccess class
DataAccess da = new DataAccess();
// The styling of the graph
chart1.Series["Series1"].ChartType = SeriesChartType.Column;
chart1.Series["Series1"].IsValueShownAsLabel = true;
// The required lines for getting the data from the method in the DataAccess
chart1.DataSource = da.select_top_sheep(farmerID);
chart1.Series["Series1"].XValueMember = "SheepID";
chart1.Series["Series1"].YValueMembers = "Weight";
chart1.DataBind();
}
Upvotes: 2
Reputation: 3480
Just need to google it: Chart sample
public void SampleCode()
{
// some code
foreach (DataRow row in myDataSet.Tables["Query"].Rows)
{
// For each Row add a new series
string seriesName = row["SalesRep"].ToString();
Chart1.Series.Add(seriesName);
Chart1.Series[seriesName].ChartType = SeriesChartType.Line;
Chart1.Series[seriesName].BorderWidth = 2;
for (int colIndex = 1; colIndex < myDataSet.Tables["Query"].Columns.Count; colIndex++)
{
// For each column (column 1 and onward) add the value as a point
string columnName = myDataSet.Tables["Query"].Columns[colIndex].ColumnName;
int YVal = (int)row[columnName];
Chart1.Series[seriesName].Points.AddXY(columnName, YVal);
}
}
DataGrid.DataSource = myDataSet;
DataGrid.DataBind();
}
Upvotes: 1