得到一个错误Null引用异常被处理

时间:2011-07-21 10:21:30

标签: c# asp.net winforms charts mschart

我试图通过使用以下

单击一个图表来显示报告图表

代码,但它显示错误

错误:处理了空引用异常           你调用的对象是空的。在此行targetcontrol.ChartAreas.Clear();

这是图表控件的点击事件

 using System.Windows.Forms.DataVisualization.Charting;


private void kpiChartControl_Click(object sender, EventArgs e)
{
  Chart targetcontrol = null;
  Series series = null;
  Title title;
  string are;

  targetcontrol.ChartAreas.Clear();
  targetcontrol.Series.Clear();
  targetcontrol.Titles.Clear();

  DataTable accepts = null;
  accepts = KPIData.AcceptedvisitsByMembership(mf ,"accepted");

 are = " acceptedvisitsmshiptypes";
  targetcontrol.ChartAreas.Add(are);
  series = targetcontrol.Series.Add(are);
  series.ChartArea = are;

  title = targetcontrol.Titles.Add("Accepted Visits By MemberShip Type");
  title.DockedToChartArea = are;
  title.Font = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Bold);
  title.Alignment = ContentAlignment.TopLeft;

  foreach (Title titles in targetcontrol.Titles)
  {
    titles.IsDockedInsideChartArea = false;
  }


  foreach (Series serie in targetcontrol.Series)
  {


    serie.ChartType = SeriesChartType.Pie;

    serie["PieLabelStyle"] = "Outside";
    serie["DoughnutRadius"] = "30";
    serie["PieDrawingStyle"] = "SoftEdge";

    serie.BackGradientStyle = GradientStyle.DiagonalLeft;


  }
  foreach (Legend legend in targetcontrol.Legends)
  {
    legend.Enabled = false;
  }

  foreach (ChartArea chartArea in targetcontrol.ChartAreas)
  {
    chartArea.Area3DStyle.Enable3D = true;
    chartArea.Area3DStyle.Inclination = 45;
    //chartArea.AxisX.LabelStyle.IsEndLabelVisible = !overview;
  }

  targetcontrol.Series[0].Points.DataBindXY(accepts.Rows, "mshiptypenumbers", accepts.Rows, "mshipType_Name");
  foreach (Series chartSeries in targetcontrol.Series)
  {
    foreach (DataPoint point in chartSeries.Points)
    {

      switch (point.AxisLabel)
      {
        case "Silver membership": point.Color = Color.Green; break;
        //case "Refused": point.Color = Color.Red; break;

      }
      point.Label = string.Format("{0:0}", point.YValues[0]);
    }

  }
}

2 个答案:

答案 0 :(得分:2)

您设置了一个变量

Chart targetcontrol = null;

然后尝试使用

targetcontrol.ChartAreas.Clear();

targetcontrol为null,没有ChartAreas属性。尝试更改第三行

Chart targetcontrol = null;

Chart targetcontrol = new Chart();

答案 1 :(得分:1)

当然你得到了那个错误,你正在声明

Chart targetcontrol = null; 

然后你试图使用它而不实际将它实例化为任何东西。