[ASP.NET] Chart 控制項X軸名稱全部顯示 Sample Code

  • 16548
  • 0

[ASP.NET] Chart 控制項X軸名稱全部顯示 Sample Code

源自:
小鋪的
一則發問,此外由於Chart Contorl的設定眉眉角角實在很多,久沒用就不容易

記得了,所以解題後順便記錄一下

問題:

Chart  X軸名稱未全部顯示

範例程式碼:

Chart Control 預設情況下X軸名稱會自動依Chart Area大小做調整,因此數量一多的時候

,X軸名稱便不會全部都顯示出來,要解決這個問題也不難,只需要設定以下屬性值

AxisX.IntervalAutoMode
AxisX.IsLabelAutoFit
AxisX.LabelStyle.IsStaggered
若您是直接於Design Time指定的話,原始碼會長的像這樣

    <Series>
        <asp:Series Name="Series1" XValueMember="name" YValueMembers="amount">
        </asp:Series>
    </Series>
    <ChartAreas>
        <asp:ChartArea Name="ChartArea1">
            <AxisX IntervalAutoMode="VariableCount" IsLabelAutoFit="False">
                <LabelStyle IsStaggered="True" />
            </AxisX>
        </asp:ChartArea>
    </ChartAreas>
</asp:Chart>

若您想於特定事件下,動態設定的話,那麼程式碼會是如下


        {
            SqlConnection conn = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DBconnStr"].ToString());

            using (SqlCommand command = new SqlCommand())
            {
                conn.Open();
                command.Connection = conn;
                command.CommandText = @"select top 20 name,RIGHT(cast(initdate as int),3) as amount  from dguser 
                                        where initdate is not null  ";
                IDataReader idr =  command.ExecuteReader();

                this.Chart1.DataSource = idr;
                this.Chart1.Series[0].XValueMember = "name";
                this.Chart1.Series[0].YValueMembers = "amount";
                this.Chart1.ChartAreas["ChartArea1"].AxisX.IntervalAutoMode = System.Web.UI.DataVisualization.Charting.IntervalAutoMode.VariableCount;
                this.Chart1.ChartAreas["ChartArea1"].AxisX.IsLabelAutoFit = false;
                this.Chart1.ChartAreas["ChartArea1"].AxisX.LabelStyle.IsStaggered = true;
                this.Chart1.DataBind();               
                idr.Dispose();
            }
        }

PS:範例程式碼僅提供示範使用,若用於正式開發,請自行加上應有的嚴僅的判斷,例如 try catch

 

 

若本文對您有所幫助,歡迎轉貼,但請在加註【轉貼】及來源出處,並在附上本篇的超連結,感恩您的配合囉。

By No.18