代码之家  ›  专栏  ›  技术社区  ›  phyllis diller

ASP.NET图表控件-动态添加和删除一系列数据点

  •  3
  • phyllis diller  · 技术社区  · 16 年前

    我有一个自定义控件,用于在UI中创建、删除和修改系列列表。单击按钮后,将使用这些序列创建图表。但是,如果我尝试重新显示图表(即使是相同的系列),它会爆炸并抛出NullReferenceException。

    以下是相关代码-我有一个对象包装系列(因为我有一些自定义属性)

    public class DataSeries
    {
        private Series _series = new Series();
        ... (bunch of other properties)
        public Series Series
        {
            get { return _series; }
            set { _series = value; }
        }
    }
    

    private static List<DataSeries> seriesList;
    
    public List<DataSeries> ListOfSeries
        {
            get { return seriesList; }
            set { seriesList = value; }
        }
    
    protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                seriesList = new List<DataSeries>();
            }
        }
    

    然后,我有一些混合控件,可以用来添加新的数据系列、删除它们以及修改它们的属性。这一切都有效。

    当他们单击页面上的“创建图表”时,将执行以下代码:

    protected void refreshChart(object sender, EventArgs e)
    {
        chart.Series.Clear();
    
            foreach (DataSeries s in seriesControl.ListOfSeries)
            {
                string propertyName = s.YAxisProperty;
    
                //List of data to display for this series 
                List<Sampled_Data> sampleList = Sample.GetSamplesById(s.ComponentId);
    
                foreach (Sampled_Data dSample in sampleList)
                {
                    //GetPropertyValue returns a float associated with the propertyname
                    //selected for displaying as the Y Value
                    s.Series.Points.AddY(BindingLib.GetPropertyValue(dSample, propertyName));
                }
                chart.Series.Add(s.Series);
            }
        }
    

    我第一次执行这段代码时,它就像一个符咒。 第二次单击执行“refreshChart”的按钮时,我得到一个NullReferenceException,因为“s.Series.Points”的值为null。我无法创建Points属性类型的新对象-其构造函数是私有的或受保护的。

    如果我没有在这个函数的后续调用之间操作Points属性,为什么它会变为null?

    我可能会想到一些解决方案——让DataSeries继承一个系列而不是一个系列——如果错误仍然存在,我可能会重新创建Points属性。我还可以深度复制系列列表,看看这是否解决了我的问题。我也可以将我所有的自定义属性放入Series对象中——它有一个customfields属性(或类似的名称)。如果我没有传递一个包裹另一个的对象,这可能会消除这个问题。

    1 回复  |  直到 16 年前
        1
  •  5
  •   Community Mohan Dere    9 年前

    我不是100%确定,但我怀疑

    chart.Series.Clear();
    

    直接清除内部 Series 您的静态成员的 seriesList 因为那条线

    chart.Series.Add(s.Series);
    

    系列 到图表上。

    您可以通过删除getter来检查此假设:

    set { seriesList = value; }
    

    此时,代码应该在

    chart.Series.Clear();
    

    刷新时:不允许图表清除您的 系列 在静态成员中

    你为什么要使用 静止的

    this answer 不幸的是 系列 未标记为[可序列化]。

    // Do you want to write this Property? copying all fields of Series Manually?
    chart.Series.Add(s.DeepCopyOfMySeries); 
    

    祝你好运