Search code examples
c#mysqlasp.netmschartlinegraph

ASP.Net C# - Set and display x axis values in Chart


I've got a function to draw a line graph as shown below. The data points are obtained from a MySQL table. However, how can I number each data point in the x axis 1,2,3,4...?

In the example below, the query returns two results and the graph displays the two points so the graph should have 1 and 2 marked on the axis.

EDIT: Initial problem solved. However, for the example above, there are 2 data points but the max x value is 3. Is there a way of setting the maximum x value to equal the number of data points?

line graph

protected void chart(int moduleID)
{
    string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
    MySqlConnection conn = new MySqlConnection(connStr);

    string comm = "SELECT * FROM scores WHERE test_id=0 AND module_id=@ModuleID AND user_id=@UserID";
    MySqlCommand mySqlCommand = new MySqlCommand(comm, conn);
    mySqlCommand.Parameters.Add(new MySqlParameter("@ModuleID", moduleID));
    mySqlCommand.Parameters.Add(new MySqlParameter("@UserID", Session["UserID"]));

    MySqlDataAdapter dataAdapter = new MySqlDataAdapter(mySqlCommand);
    DataTable ds = new DataTable();

    Chart1.ChartAreas["ChartArea1"].AxisX.MajorGrid.Enabled = false;
    Chart1.ChartAreas["ChartArea1"].AxisY.MajorGrid.Enabled = false;
    Chart1.ChartAreas["ChartArea1"].AxisX.Minimum = 1;
    Chart1.ChartAreas["ChartArea1"].AxisX.LabelStyle.Enabled = false;
    Chart1.ChartAreas["ChartArea1"].AxisX.Title = "attempt no.";
    Chart1.ChartAreas["ChartArea1"].AxisY.Minimum = 0;
    Chart1.ChartAreas["ChartArea1"].AxisY.Maximum = 100;
    Chart1.ChartAreas["ChartArea1"].AxisY.Title = "%";
    Chart1.ChartAreas["ChartArea1"].AxisY.TextOrientation = TextOrientation.Horizontal;

    try
    {
        conn.Open();
        dataAdapter.Fill(ds);

        if (ds.Rows.Count > 0)
        {
            Chart1.DataSource = ds;
            Chart1.Series["Series1"].YValueMembers = "score";
            Chart1.DataBind();
        }
        else
        {
            Chart1.Visible = false;
            lblError2.Text = "No results found.";
        }
    }
    catch
    {
        lblError.Text = "Database connection error. Unable to obtain data at the moment.";
    }
    finally
    {
        conn.Close();
    }
}

Solution

  • There is problem with:

    Chart1.ChartAreas["ChartArea1"].AxisX.LabelStyle.Enabled = false;
    

    You have disbled AxisX labels

    http://msdn.microsoft.com/en-us/library/system.windows.forms.datavisualization.charting.labelstyle.enabled%28v=vs.110%29.aspx