2017-02-22 42 views
0

我正在嘗試創建一組圖表系列,將數據添加到系列中,然後通過顯示系列中的一些來顯示系列。數據發生變化,用戶可以選擇要查看的系列。我認爲這種方法會比用chart.Series.Clear();清除所有系列,然後用相同的方法重新創建系列更好。創建圖表系列,添加數據並設置知名度

例如拼車隨機里程的汽車列表,然後選擇要顯示哪些車。

下面的代碼不起作用(我評論說在哪裏)。該系列不公開,我認爲他們需要添加到公共集合,如SeriesCollection,但我不知道如何。

感謝您的任何幫助。

// create new chart series and add to a chartarea 
     ChartArea TestChartArea = new ChartArea(); 
     public void CreateChartSeries() 
     { 
      List<string> lstCars = new List<string> { "Mazda", "Tesla", "Honda", "Jaguar", "Ford", "Toyota" }; 

      foreach (string Car in lstCars) 
      { 
       // car series created correctly? 
       var Srs = new Series(Car); 
       Srs.ChartArea = TestChart.Name; 
       Srs.YAxisType = AxisType.Primary; 
       Srs.Color = Color.Red; 
       Srs.ChartType = SeriesChartType.Line; 
       TestChart.Series.Add(Srs); 
      } 
     } 

     // add data to chart series 
     public void SeriesData() 
     { 
      List<string> lstCars = new List<string> { "Mazda", "Tesla", "Honda", "Jaguar", "Ford", "Toyota" }; 
      int[] Xseries = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 
      int[] Milage = new int[10]; 

      Random Random = new Random(); 

      foreach (string Car in lstCars) 
      { 
       for (int M = 0; M < 10; M++) 
        Milage[M] = Random.Next(150, 15000); 

       // not sure how to call and add data to each series 
       Srs.Points.DataBindXY(Xseries, Milage); 
      } 
     } 

     // plot series - some visible 
     public void PlotCreatedSeries() 
     { 
      // not sure how to refer to each series 
      Mazda.Enabled = true; 
      Tesla.Enabled = false; 
      Honda.Enabled = true; 
      Jaguar.Enabled = false; 
      Ford.Enabled = true; 
      Toyota.Enabled = false; 
     } 

回答

1

'Srs'您使用創建Series僅在範圍,即在循環中使用的名稱。在循環結束時,你做添加新創建的SeriesChart

TestChart.Series.Add(Srs); 

Series財產公共SeriesCollection。這是一個有點混亂,因爲奇異類型名稱和多屬性名在這種情況下,同樣的,作爲反對,說,Legend(s)ChartArea(s) ..

從現在開始,你可以訪問它按索引..

Series s = TestChart.Series[0] // the series you have added first 

..或者,更易讀,更穩定,其Name屬性:

Series s = TestChart.Series["Mazda"] // the same series 

TestChart.Series["Mazda"].Enabled = true; 

注意'name'也是一個棘手的詞:

當你聲明一個變量時,你給它一個'名字'。 Series s = new Series();

但是很多對象也有財產稱爲Names.Name = "Volvo";

前者必須是唯一的,但後者只是一個字符串;也要保持它的獨特性,但系統不會保護你。

前者永遠不會改變,但正如你所見,它可能超出範圍;後者只是一個字符串,你可以改變它。

注意變量本身不出去SCOP的,只要它仍然是地方引用,在這裏爲SeriesiesCollection Series的元素..

是否要添加DataPoints約束是直接由你決定。

對於前者有many binding選項。

對於後者,你可以使用Chart.Points methods ..:

  • Add(DataPoint)
  • AddY(YValue)
  • AddXY(XValues, YValue(s))

注意,有時,尤其是對於現場圖是有道理的插入 a DataPoint使用之一方法!

請在MSDN中查看!中間版本只有在x值是非數字或不具有真正含義的情況下才有意義,例如名稱。 - 請注意,將有意義的x值添加爲號碼(或DateTimes)對於使用至關重要他們爲進一步的目標,如工具提示,縮放或顯示範圍等。

未能這樣做可能是最常見的錯誤新手。 Chart看起來不錯,但裏面的數據被破壞,讀取丟失。

+0

謝謝TaW - 在你的幫助下,我得到了工作的代碼! – Zeus

相關問題