C# 超出或范围异常图表

C# out or range exception Chart

大家好,我正在尝试在 C# 中创建更新折线图,但我一直在 chart1.Series[0].Points[0].XValue. 上收到超出范围的异常 我的代码是这样的:

        {    
    _valueList.Add(mspk);
    chart1.ResetAutoValues();

    if (chart1.Series[0].Points.Count > 0)
        {

            while (chart1.Series[0].Points[0].XValue < chart1.ChartAreas[0].AxisX.Minimum+5000)
            {

                    chart1.ChartAreas[0].AxisX.Minimum = chart1.Series[0].Points[0].XValue - 5000;
                    chart1.ChartAreas[0].AxisX.Maximum = chart1.Series[0].Points[0].XValue + 5000;
                    chart1.Series[0].Points.RemoveAt(0);
            }

        }
    chart1.Series[0].Points.AddXY(inst, _valueList[_valueList.Count - 1]);
    chart1.Invalidate();
    }

我对 C# 的经验不是很丰富,所以我尝试修改这段使用随机数的代码。从随机数切换到我的输入没有问题,但我似乎无法弄清楚如何用我的数据替换时间

        private void AddData()
    {
        DateTime now = DateTime.Now;
        //Insert a number into the list.
        _valueList.Add(_ran.Next(0, 100));


        chart1.ResetAutoValues();

        //Remove old datas from the chart.
        if (chart1.Series[0].Points.Count > 0)
        {
            while (chart1.Series[0].Points[0].XValue < now.AddSeconds(-5).ToOADate())
            {
                chart1.Series[0].Points.RemoveAt(0);

                chart1.ChartAreas[0].AxisX.Minimum = chart1.Series[0].Points[0].XValue;
                chart1.ChartAreas[0].AxisX.Maximum = now.AddSeconds(5).ToOADate();
            }
        }

        //Insert a data into the chart.

        chart1.Series[0].Points.AddXY(now.ToOADate(), _valueList[_valueList.Count - 1]);

        chart1.Invalidate();
    }

提前致谢

确保 chart1.Series[0] 在尝试访问其属性之前存在。

    private void AddData()
{
    DateTime now = DateTime.Now;
    //Insert a number into the list.
    _valueList.Add(_ran.Next(0, 100));


    chart1.ResetAutoValues();

    if(chart1.Series.Count==0) // Check to make sure Series 0 exists
    {
        chart1.Series.Add("Series 1"); // If it doesn't exist then create it.
    }

    //Remove old datas from the chart.
    if (chart1.Series[0].Points.Count > 0)
    {
        while (chart1.Series[0].Points[0].XValue < now.AddSeconds(-5).ToOADate())
        {
            chart1.Series[0].Points.RemoveAt(0);

            chart1.ChartAreas[0].AxisX.Minimum = chart1.Series[0].Points[0].XValue;
            chart1.ChartAreas[0].AxisX.Maximum = now.AddSeconds(5).ToOADate();
        }
    }

    //Insert a data into the chart.

    chart1.Series[0].Points.AddXY(now.ToOADate(), _valueList[_valueList.Count - 1]);

    chart1.Invalidate();
}