在显示图表之前它不会计算最大值,因此以下代码显示 NaN:
public Form1()
{
InitializeComponent();
this.chart1.Series.Clear();
this.chart1.Series.Add("My Data");
this.chart1.Series[0].Points.AddXY(1, 1);
this.chart1.Series[0].Points.AddXY(2, 2);
this.chart1.Series[0].Points.AddXY(3, 6);
MessageBox.Show(this.chart1.ChartAreas[0].AxisY.Maximum.ToString()); // returns NaN
}
但是在图表显示后检查会给出正确的值:
public Form1()
{
InitializeComponent();
this.chart1.Series.Clear();
this.chart1.Series.Add("My Data");
this.chart1.Series[0].Points.AddXY(1, 1);
this.chart1.Series[0].Points.AddXY(2, 2);
this.chart1.Series[0].Points.AddXY(3, 6);
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(this.chart1.ChartAreas[0].AxisY.Maximum.ToString()); // returns 8
}
或者,您可以在设置数据后立即执行更新(但这在表单构造函数中不起作用,因为图表尚未显示):
private void button1_Click(object sender, EventArgs e)
{
this.chart1.Series.Clear();
this.chart1.Series.Add("My Data");
this.chart1.Series[0].Points.AddXY(1, 1);
this.chart1.Series[0].Points.AddXY(2, 2);
this.chart1.Series[0].Points.AddXY(3, 6);
this.chart1.Update();
MessageBox.Show(this.chart1.ChartAreas[0].AxisY.Maximum.ToString()); // returns 8
}
这是使用 OnShown Form 事件和两个数据系列的另一种方法:
public Form1()
{
InitializeComponent();
this.chart1.Series.Clear();
this.chart1.Series.Add("My Data");
this.chart1.Series[0].Points.AddXY(1, 1);
this.chart1.Series[0].Points.AddXY(2, 2);
this.chart1.Series[0].Points.AddXY(3, 6);
this.chart1.Series.Add("My Data2");
this.chart1.Series[1].Points.AddXY(1, 1);
this.chart1.Series[1].Points.AddXY(2, 9);
}
protected override void OnShown(EventArgs e)
{
base.OnShown(e);
this.chart1.Update();
MessageBox.Show(this.chart1.ChartAreas[0].AxisY.Maximum.ToString()); // returns 10
}