Arif Sam Arif Sam - 1 month ago 15
ASP.NET (C#) Question

Chart Not Showing All Data

So i just started learning MVC, and Im learning to produce graph.
Im trying to pull data from SQL server and place it in X and Y axis.
My problem is, on the y axis, it populate till the end of my db but my x axis only shows 1 data from db.
Or am i doing everything wrong?
Do help. TQVM.

controller code:

public ActionResult MyBarGraph()
{
DB.Open();
DataTable data = DB.GetTable("SELECT * FROM tblproduct");
DB.Close();
Chart c = new Chart(width: 800, height: 200);
foreach(DataRow item in data.Rows)
{
c.AddSeries(
chartType: "column",
xValue: new[] {item["productname"]},
yValues: new[] { item["quantity"] });
}
c.Write("png");

return null;
}


view code:

<div>
<h2>Bar Graph Example</h2>
<img src="@Url.Action("MyBarGraph")" alt="SimpleChart" />
</div>


image :

only Apple is shown

updated-image:

new problem

Answer

You should use this syntax instead:

            var myChart = new Chart(width: 600, height: 400)
            .AddTitle("Product Chart")
            .AddSeries(
            name: "Products",
            xValue: data.AsDataView(), xField: "productname",
            yValues: data.AsDataView(), yFields: "quantity")
            .Save("~/Images/Chart01.png", "png");

enter image description here


EDIT: In order to customize your labels you need to pass a Theme file to your chart, like this:

            var myChart = new Chart(width: 600, height: 400, themePath: "MyTheme.xml")
            .AddTitle("Product Chart")
            .AddSeries(
            name: "Products",
            xValue: data.AsDataView(), xField: "productname",
            yValues: data.AsDataView(), yFields: "quantity")
            .Save("~/Images/Chart01.png", "png");

Add MyTheme.xml file to the root folder of your project, with the following content:

<?xml version="1.0" encoding="utf-8" ?>
<Chart>
  <ChartAreas>
    <ChartArea Name="Default">
      <AxisX IsLabelAutoFit="false">
        <LabelStyle Angle="-90" Interval="1"></LabelStyle>
      </AxisX>
    </ChartArea>
  </ChartAreas>
</Chart>

enter image description here