Search code examples
c#visual-studiochartscolumn-chartdotnetcharting

C# Column Chart skips XValueMember value but displays YValueMember value


Code

        DataSet ds = new DataSet();
        con.Open();
        SqlDataAdapter adapt = new SqlDataAdapter("select top 10 p.customername, ISNULL(SUM(c.total),0) as total from table_customerpurchases as c Left join table_customers as p on p.customerid = c.cid where cid!='Default' and cid!='c10022' group by customername order by total desc", con);
        adapt.Fill(ds);
        chart1.DataSource = ds;
       
        chart1.Series["Customers"].XValueMember = "customername";
        chart1.Series["Customers"].XValueType = ChartValueType.String;
        
        chart1.Series["Customers"].YValueMembers = "total";
        chart1.Series["Customers"].YValueType = ChartValueType.Double;
        chart1.Titles.Add("Customers Purchases Chart");
        chart1.Series["Customers"].IsValueShownAsLabel = true;
        con.Close();

Output Result Picture of Column Chart Picture of Column Chart

As you can see when i put break there and see in dataset visualizer; All data is filled in there Dataset Values Picture

> Problem Description

I don't know where the problem is that it is showing column bar but skips 'XValueMember' value. Also why it is not creating separate column line for every 'XValueMember'.


Solution

  • 您只需要在代码中添加以下三行代码即可:

    chart1.ChartAreas[0].AxisX.Interval = 1; //Set the X axis coordinate interval to 1
    chart1.ChartAreas[0].AxisX.IntervalOffset = 1; //Set the X axis coordinate offset to 1
    chart1.ChartAreas[0].AxisX.LabelStyle.IsStaggered = true; //Set whether to display staggered, for example, the time with a lot of data is divided into two rows to display
    

    Output:

    enter image description here

    Or like this:

    //chart1.ChartAreas[0].AxisX.LabelStyle.IsStaggered = true;
    chart1.ChartAreas[0].AxisX.LabelStyle.Angle=90//Rotate 90 degrees;
    

    Output: enter image description here