[C#] 使用Chart類別建立不含格線的直條圖

摘要:[C#] 使用Chart類別建立不含格線的直條圖

依據預設,當程式建立一個 Chart ,X Y軸均會有格線 。如下圖:

但如果只要顯示 X=5 跟 Y = 0 的這兩條呢? 如下圖 :

 

很簡單,只要將X Y 軸的MajorGrid 的 LineWidth屬性設定為0 就可以了

程式如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.DataVisualization.Charting;
using System.Drawing;
namespace TestChart
{
    public partial class index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        private void CreateChart()
        {
            using (Chart chart = new Chart())
            {
                ChartArea area = chart.ChartAreas.Add("chartArea");
                area.Visible = true;

                area.AxisX.MajorGrid.LineWidth = 0;
                area.AxisX2.Enabled = AxisEnabled.False;

                area.AxisY.MajorGrid.LineWidth = 0;
                area.AxisY2.Enabled = AxisEnabled.False;

                Series series = chart.Series.Add("firstSeries");
                series.ChartType = SeriesChartType.Column;

                Random r = new Random(Guid.NewGuid().GetHashCode());

                for (int i = 5; i < 50; i += 5)
                {
                    series.Points.AddXY(i, r.Next(5, 30));
                }

                series.XAxisType = AxisType.Primary;
                series.YAxisType = AxisType.Primary;
                series.Color = Color.Cyan;
                series.ChartArea = area.Name;
                series.Enabled = true;

                string exportFileName = Server.MapPath(".") + "/testImage.jpg";
                chart.SaveImage(exportFileName, ChartImageFormat.Jpeg);
                this.ClientScript.RegisterStartupScript(this.GetType(), "exportChart", string.Format("alert('已成功匯出至:{0}');", exportFileName.Replace('\\','/')), true);
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            CreateChart();
        }
    }
}

 

 

範例檔