如何编辑asp.net图表X轴标签,仅显示日期而不是时间

时间:2016-10-04 13:59:06

标签: c# asp.net charts

enter image description here

如何从图表中的X轴中删除时间。 我的sql仅返回日期,但我的代码再次添加时间。

我试过了:

Chart1.ChartAreas[0].AxisX.LabelStyle.Format = "##-##-##";

但没有运气。

我目前的代码:

            Chart1.Visible = ddlChart.SelectedValue != "";
            string query = string.Format(stest);
            DataTable dt = GetData(query);
            string[] x = new string[dt.Rows.Count];
            int[] y = new int[dt.Rows.Count];
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                x[i] = dt.Rows[i][0].ToString();
                y[i] = Convert.ToInt32(dt.Rows[i][1]);
            }
            Chart1.Series[0].Points.DataBindXY(x, y);

            Chart1.Series[0].ChartType = SeriesChartType.Bar;
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;
            Chart1.Legends[0].Enabled = true;

工作代码 - 谢谢jstreet

Chart1.Visible = ddlChart.SelectedValue != "";
            string query = string.Format(stest);
            DataTable dt = GetData(query);

            DateTime[] x = new DateTime [dt.Rows.Count];
            int[] y = new int[dt.Rows.Count];
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                x[i] = Convert.ToDateTime(dt.Rows[i][0]);
                y[i] = Convert.ToInt32(dt.Rows[i][1]);
            }
            Chart1.Series[0].Points.DataBindXY(x, y);

            Chart1.ChartAreas[0].AxisX.LabelStyle.Format = "MM-dd-yyyy";

            Chart1.Series[0].ChartType = SeriesChartType.Bar;

            Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;

            Chart1.Legends[0].Enabled = true;

2 个答案:

答案 0 :(得分:3)

Bar图表中(与Column图表相对),纵轴为AxisX,而非AxisY。另外,请避免为AxisX分配字符串。根本没有必要,可能会导致问题。

使用此:

Chart1.ChartAreas[0].AxisX.LabelStyle.Format = "MM-dd-yyyy";

或者这个:

Chart1.ChartAreas[0].AxisX.LabelStyle.Format = "MM-dd-yy";

enter image description here

修改

以下是一些示例代码:

    protected void Page_Load(object sender, EventArgs e)
    {
        DateTime[] x = new DateTime[3];
        int[] y = new int[3];

        for (int i = 0; i < 3; i++)
        {
            x[i] = DateTime.Now.AddDays(i);
            y[i] = 10 * (i + 1);
        }
        Chart1.Series[0].Points.DataBindXY(x, y);
        Chart1.ChartAreas[0].AxisX.LabelStyle.Format = "MM-dd-yy";
    }

答案 1 :(得分:0)

以下内容应该有效

 for (int i=0; i < dt.Rows.Count; i++)
 {
     DataRow row = dt.Rows[i];
     x[i] = DateTime.ParseExact(row[0].ToString(), 'MM-dd-yy', CultureInfo.InvariantCulture);
     y[i] = Convert.ToInt32(row[1]);
 }