Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2870_AutoDiff-nuget/HeuristicLab.Data.Views/3.3/StringConvertibleMatrixView.cs @ 16793

Last change on this file since 16793 was 15583, checked in by swagner, 7 years ago

#2640: Updated year of copyrights in license headers

File size: 23.7 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.ComponentModel;
25using System.Drawing;
26using System.Linq;
27using System.Text;
28using System.Windows.Forms;
29using HeuristicLab.Common;
30using HeuristicLab.MainForm;
31using HeuristicLab.MainForm.WindowsForms;
32
33namespace HeuristicLab.Data.Views {
34  [View("StringConvertibleMatrix View")]
35  [Content(typeof(IStringConvertibleMatrix), true)]
36  public partial class StringConvertibleMatrixView : AsynchronousContentView {
37    protected int[] virtualRowIndices;
38    protected List<KeyValuePair<int, SortOrder>> sortedColumnIndices;
39    private RowComparer rowComparer;
40
41    public new IStringConvertibleMatrix Content {
42      get { return (IStringConvertibleMatrix)base.Content; }
43      set { base.Content = value; }
44    }
45
46    public DataGridView DataGridView {
47      get { return dataGridView; }
48    }
49
50    public override bool ReadOnly {
51      get {
52        if ((Content != null) && Content.ReadOnly) return true;
53        return base.ReadOnly;
54      }
55      set { base.ReadOnly = value; }
56    }
57
58    private bool showRowsAndColumnsTextBox;
59    public bool ShowRowsAndColumnsTextBox {
60      get { return showRowsAndColumnsTextBox; }
61      set {
62        showRowsAndColumnsTextBox = value;
63        UpdateVisibilityOfTextBoxes();
64      }
65    }
66
67    private bool showStatisticalInformation;
68    public bool ShowStatisticalInformation {
69      get { return showStatisticalInformation; }
70      set {
71        showStatisticalInformation = value;
72        UpdateVisibilityOfStatisticalInformation();
73      }
74    }
75
76    public StringConvertibleMatrixView() {
77      InitializeComponent();
78      ShowRowsAndColumnsTextBox = true;
79      ShowStatisticalInformation = true;
80      errorProvider.SetIconAlignment(rowsTextBox, ErrorIconAlignment.MiddleLeft);
81      errorProvider.SetIconPadding(rowsTextBox, 2);
82      errorProvider.SetIconAlignment(columnsTextBox, ErrorIconAlignment.MiddleLeft);
83      errorProvider.SetIconPadding(columnsTextBox, 2);
84      sortedColumnIndices = new List<KeyValuePair<int, SortOrder>>();
85      rowComparer = new RowComparer();
86    }
87
88    protected override void DeregisterContentEvents() {
89      Content.ItemChanged -= new EventHandler<EventArgs<int, int>>(Content_ItemChanged);
90      Content.Reset -= new EventHandler(Content_Reset);
91      Content.ColumnNamesChanged -= new EventHandler(Content_ColumnNamesChanged);
92      Content.RowNamesChanged -= new EventHandler(Content_RowNamesChanged);
93      base.DeregisterContentEvents();
94    }
95    protected override void RegisterContentEvents() {
96      base.RegisterContentEvents();
97      Content.ItemChanged += new EventHandler<EventArgs<int, int>>(Content_ItemChanged);
98      Content.Reset += new EventHandler(Content_Reset);
99      Content.ColumnNamesChanged += new EventHandler(Content_ColumnNamesChanged);
100      Content.RowNamesChanged += new EventHandler(Content_RowNamesChanged);
101    }
102
103    protected override void OnContentChanged() {
104      base.OnContentChanged();
105      if (Content == null) {
106        rowsTextBox.Text = "";
107        columnsTextBox.Text = "";
108        dataGridView.Rows.Clear();
109        dataGridView.Columns.Clear();
110        virtualRowIndices = new int[0];
111      } else if (!dataGridView.IsCurrentCellInEditMode) {
112        UpdateData();
113      }
114    }
115
116    protected override void SetEnabledStateOfControls() {
117      base.SetEnabledStateOfControls();
118      rowsTextBox.Enabled = Content != null;
119      columnsTextBox.Enabled = Content != null;
120      dataGridView.Enabled = Content != null;
121      rowsTextBox.ReadOnly = ReadOnly;
122      columnsTextBox.ReadOnly = ReadOnly;
123      dataGridView.ReadOnly = ReadOnly;
124    }
125
126    protected virtual void UpdateData() {
127      rowsTextBox.Text = Content.Rows.ToString();
128      rowsTextBox.Enabled = true;
129      columnsTextBox.Text = Content.Columns.ToString();
130      columnsTextBox.Enabled = true;
131      virtualRowIndices = Enumerable.Range(0, Content.Rows).ToArray();
132
133
134      dataGridView.RowCount = 0;
135
136      DataGridViewColumn[] columns = new DataGridViewColumn[Content.Columns];
137      for (int i = 0; i < columns.Length; ++i) {
138        var column = new DataGridViewTextBoxColumn();
139        column.SortMode = DataGridViewColumnSortMode.Programmatic;
140        column.FillWeight = 1;
141        columns[i] = column;
142      }
143      dataGridView.Columns.Clear();
144
145      if (Content.Columns != 0) {
146        dataGridView.Columns.AddRange(columns);
147        dataGridView.RowCount = Content.Rows;
148      }
149
150      ClearSorting();
151      UpdateColumnHeaders();
152      UpdateRowHeaders();
153
154      dataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.ColumnHeader);
155      dataGridView.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders);
156      dataGridView.Enabled = true;
157    }
158
159    public virtual void UpdateColumnHeaders() {
160      HashSet<string> invisibleColumnNames = new HashSet<string>(dataGridView.Columns.OfType<DataGridViewColumn>()
161      .Where(c => !c.Visible && !string.IsNullOrEmpty(c.HeaderText)).Select(c => c.HeaderText));
162
163      for (int i = 0; i < dataGridView.ColumnCount; i++) {
164        if (i < Content.ColumnNames.Count())
165          dataGridView.Columns[i].HeaderText = Content.ColumnNames.ElementAt(i);
166        else
167          dataGridView.Columns[i].HeaderText = "Column " + (i + 1);
168        dataGridView.Columns[i].Visible = !invisibleColumnNames.Contains(dataGridView.Columns[i].HeaderText);
169      }
170    }
171    public virtual void UpdateRowHeaders() {
172      int index = dataGridView.FirstDisplayedScrollingRowIndex;
173      if (index == -1) index = 0;
174      int updatedRows = 0;
175      int count = dataGridView.DisplayedRowCount(true);
176
177      while (updatedRows < count) {
178        if (virtualRowIndices[index] < Content.RowNames.Count())
179          dataGridView.Rows[index].HeaderCell.Value = Content.RowNames.ElementAt(virtualRowIndices[index]);
180        else
181          dataGridView.Rows[index].HeaderCell.Value = "Row " + (index + 1);
182        if (dataGridView.Rows[index].Visible)
183          updatedRows++;
184        index++;
185      }
186    }
187
188    private void Content_RowNamesChanged(object sender, EventArgs e) {
189      if (InvokeRequired)
190        Invoke(new EventHandler(Content_RowNamesChanged), sender, e);
191      else
192        UpdateRowHeaders();
193    }
194    private void Content_ColumnNamesChanged(object sender, EventArgs e) {
195      if (InvokeRequired)
196        Invoke(new EventHandler(Content_ColumnNamesChanged), sender, e);
197      else
198        UpdateColumnHeaders();
199    }
200    private void Content_ItemChanged(object sender, EventArgs<int, int> e) {
201      if (InvokeRequired)
202        Invoke(new EventHandler<EventArgs<int, int>>(Content_ItemChanged), sender, e);
203      else
204        dataGridView.InvalidateCell(e.Value2, e.Value);
205    }
206    private void Content_Reset(object sender, EventArgs e) {
207      if (InvokeRequired)
208        Invoke(new EventHandler(Content_Reset), sender, e);
209      else
210        UpdateData();
211    }
212
213    #region TextBox Events
214    private void rowsTextBox_Validating(object sender, CancelEventArgs e) {
215      if (ReadOnly || Locked)
216        return;
217      int i = 0;
218      if (!int.TryParse(rowsTextBox.Text, out i) || (i <= 0)) {
219        e.Cancel = true;
220        errorProvider.SetError(rowsTextBox, "Invalid Number of Rows (Valid values are positive integers larger than 0)");
221        rowsTextBox.SelectAll();
222      }
223    }
224    private void rowsTextBox_Validated(object sender, EventArgs e) {
225      if (!Content.ReadOnly) Content.Rows = int.Parse(rowsTextBox.Text);
226      errorProvider.SetError(rowsTextBox, string.Empty);
227    }
228    private void rowsTextBox_KeyDown(object sender, KeyEventArgs e) {
229      if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
230        rowsLabel.Focus();  // set focus on label to validate data
231      if (e.KeyCode == Keys.Escape) {
232        rowsTextBox.Text = Content.Rows.ToString();
233        rowsLabel.Focus();  // set focus on label to validate data
234      }
235    }
236    private void columnsTextBox_Validating(object sender, CancelEventArgs e) {
237      if (ReadOnly || Locked)
238        return;
239      int i = 0;
240      if (!int.TryParse(columnsTextBox.Text, out i) || (i <= 0)) {
241        e.Cancel = true;
242        errorProvider.SetError(columnsTextBox, "Invalid Number of Columns (Valid values are positive integers larger than 0)");
243        columnsTextBox.SelectAll();
244      }
245    }
246    private void columnsTextBox_Validated(object sender, EventArgs e) {
247      if (!Content.ReadOnly) Content.Columns = int.Parse(columnsTextBox.Text);
248      errorProvider.SetError(columnsTextBox, string.Empty);
249    }
250    private void columnsTextBox_KeyDown(object sender, KeyEventArgs e) {
251      if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
252        columnsLabel.Focus();  // set focus on label to validate data
253      if (e.KeyCode == Keys.Escape) {
254        columnsTextBox.Text = Content.Columns.ToString();
255        columnsLabel.Focus();  // set focus on label to validate data
256      }
257    }
258    #endregion
259
260    #region DataGridView Events
261
262    protected virtual void dataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) {
263      if (dataGridView.ReadOnly) return;
264      if (Content == null) return;
265      if (Content.Rows <= e.RowIndex || Content.Columns <= e.ColumnIndex) return;
266
267      string errorMessage;
268      if (!Content.Validate(e.FormattedValue.ToString(), out errorMessage)) {
269        e.Cancel = true;
270        dataGridView.Rows[e.RowIndex].ErrorText = errorMessage;
271      }
272    }
273
274    protected virtual void dataGridView_CellParsing(object sender, DataGridViewCellParsingEventArgs e) {
275      if (!dataGridView.ReadOnly) {
276        string value = e.Value.ToString();
277        int rowIndex = virtualRowIndices[e.RowIndex];
278        e.ParsingApplied = Content.SetValue(value, rowIndex, e.ColumnIndex);
279        if (e.ParsingApplied) e.Value = Content.GetValue(rowIndex, e.ColumnIndex);
280      }
281    }
282    private void dataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e) {
283      dataGridView.Rows[e.RowIndex].ErrorText = string.Empty;
284    }
285    protected virtual void dataGridView_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e) {
286      if (Content != null && e.RowIndex < Content.Rows && e.ColumnIndex < Content.Columns) {
287        int rowIndex = virtualRowIndices[e.RowIndex];
288        e.Value = Content.GetValue(rowIndex, e.ColumnIndex);
289      }
290    }
291
292    private void dataGridView_Scroll(object sender, System.Windows.Forms.ScrollEventArgs e) {
293      this.UpdateRowHeaders();
294    }
295    private void dataGridView_Resize(object sender, EventArgs e) {
296      this.UpdateRowHeaders();
297    }
298
299    protected virtual void dataGridView_KeyDown(object sender, KeyEventArgs e) {
300      if (!ReadOnly && e.Control && e.KeyCode == Keys.V)
301        PasteValuesToDataGridView();
302      else if (e.Control && e.KeyCode == Keys.C)
303        CopyValuesFromDataGridView();
304    }
305
306    private void CopyValuesFromDataGridView() {
307      if (dataGridView.SelectedCells.Count == 0) return;
308      StringBuilder s = new StringBuilder();
309      int minRowIndex = dataGridView.SelectedCells[0].RowIndex;
310      int maxRowIndex = dataGridView.SelectedCells[dataGridView.SelectedCells.Count - 1].RowIndex;
311      int minColIndex = dataGridView.SelectedCells[0].ColumnIndex;
312      int maxColIndex = dataGridView.SelectedCells[dataGridView.SelectedCells.Count - 1].ColumnIndex;
313
314      if (minRowIndex > maxRowIndex) {
315        int temp = minRowIndex;
316        minRowIndex = maxRowIndex;
317        maxRowIndex = temp;
318      }
319      if (minColIndex > maxColIndex) {
320        int temp = minColIndex;
321        minColIndex = maxColIndex;
322        maxColIndex = temp;
323      }
324
325      bool addRowNames = dataGridView.AreAllCellsSelected(false) && Content.RowNames.Count() > 0;
326      bool addColumnNames = dataGridView.AreAllCellsSelected(false) && Content.ColumnNames.Count() > 0;
327
328      //add colum names
329      if (addColumnNames) {
330        if (addRowNames)
331          s.Append('\t');
332
333        DataGridViewColumn column = dataGridView.Columns.GetFirstColumn(DataGridViewElementStates.Visible);
334        while (column != null) {
335          s.Append(column.HeaderText);
336          s.Append('\t');
337          column = dataGridView.Columns.GetNextColumn(column, DataGridViewElementStates.Visible, DataGridViewElementStates.None);
338        }
339        s.Remove(s.Length - 1, 1); //remove last tab
340        s.Append(Environment.NewLine);
341      }
342
343      for (int i = minRowIndex; i <= maxRowIndex; i++) {
344        if (!dataGridView.Rows[i].Visible) continue;
345
346        int rowIndex = this.virtualRowIndices[i];
347        if (addRowNames) {
348          s.Append(Content.RowNames.ElementAt(rowIndex));
349          s.Append('\t');
350        }
351
352        DataGridViewColumn column = dataGridView.Columns.GetFirstColumn(DataGridViewElementStates.Visible);
353        while (column != null) {
354          DataGridViewCell cell = dataGridView[column.Index, i];
355          if (cell.Selected) {
356            s.Append(Content.GetValue(rowIndex, column.Index));
357            s.Append('\t');
358          }
359
360          column = dataGridView.Columns.GetNextColumn(column, DataGridViewElementStates.Visible, DataGridViewElementStates.None);
361        }
362        s.Remove(s.Length - 1, 1); //remove last tab
363        s.Append(Environment.NewLine);
364      }
365      Clipboard.SetText(s.ToString());
366    }
367
368    protected virtual void PasteValuesToDataGridView() {
369      string[,] values = SplitClipboardString(Clipboard.GetText());
370      int rowIndex = 0;
371      int columnIndex = 0;
372      if (dataGridView.CurrentCell != null) {
373        rowIndex = dataGridView.CurrentCell.RowIndex;
374        columnIndex = dataGridView.CurrentCell.ColumnIndex;
375      }
376      if (Content.Rows < values.GetLength(1) + rowIndex) Content.Rows = values.GetLength(1) + rowIndex;
377      if (Content.Columns < values.GetLength(0) + columnIndex) Content.Columns = values.GetLength(0) + columnIndex;
378
379      for (int row = 0; row < values.GetLength(1); row++) {
380        for (int col = 0; col < values.GetLength(0); col++) {
381          Content.SetValue(values[col, row], row + rowIndex, col + columnIndex);
382        }
383      }
384      ClearSorting();
385    }
386    protected string[,] SplitClipboardString(string clipboardText) {
387      if (clipboardText.EndsWith(Environment.NewLine))
388        clipboardText = clipboardText.Remove(clipboardText.Length - Environment.NewLine.Length);  //remove last newline constant
389      string[,] values = null;
390      string[] lines = clipboardText.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
391      string[] cells;
392      for (int i = 0; i < lines.Length; i++) {
393        cells = lines[i].Split('\t');
394        if (values == null)
395          values = new string[cells.Length, lines.Length];
396        for (int j = 0; j < cells.Length; j++)
397          values[j, i] = string.IsNullOrEmpty(cells[j]) ? string.Empty : cells[j];
398      }
399      return values;
400    }
401
402    protected virtual void dataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
403      if (Content != null) {
404        if (e.Button == MouseButtons.Left && Content.SortableView) {
405          SortColumn(e.ColumnIndex);
406        }
407      }
408    }
409
410    protected virtual void ClearSorting() {
411      virtualRowIndices = Enumerable.Range(0, Content.Rows).ToArray();
412      sortedColumnIndices.Clear();
413      UpdateSortGlyph();
414    }
415
416    protected void Sort() {
417      virtualRowIndices = Sort(sortedColumnIndices);
418      UpdateSortGlyph();
419      UpdateRowHeaders();
420      dataGridView.Invalidate();
421    }
422
423    protected virtual void SortColumn(int columnIndex) {
424      bool addToSortedIndices = (Control.ModifierKeys & Keys.Control) == Keys.Control;
425      SortOrder newSortOrder = SortOrder.Ascending;
426      if (sortedColumnIndices.Any(x => x.Key == columnIndex)) {
427        SortOrder oldSortOrder = sortedColumnIndices.Where(x => x.Key == columnIndex).First().Value;
428        int enumLength = Enum.GetValues(typeof(SortOrder)).Length;
429        newSortOrder = oldSortOrder = (SortOrder)Enum.Parse(typeof(SortOrder), ((((int)oldSortOrder) + 1) % enumLength).ToString());
430      }
431
432      if (!addToSortedIndices)
433        sortedColumnIndices.Clear();
434
435      if (sortedColumnIndices.Any(x => x.Key == columnIndex)) {
436        int sortedIndex = sortedColumnIndices.FindIndex(x => x.Key == columnIndex);
437        if (newSortOrder != SortOrder.None)
438          sortedColumnIndices[sortedIndex] = new KeyValuePair<int, SortOrder>(columnIndex, newSortOrder);
439        else
440          sortedColumnIndices.RemoveAt(sortedIndex);
441      } else
442        if (newSortOrder != SortOrder.None)
443        sortedColumnIndices.Add(new KeyValuePair<int, SortOrder>(columnIndex, newSortOrder));
444      Sort();
445    }
446
447    protected virtual int[] Sort(IEnumerable<KeyValuePair<int, SortOrder>> sortedColumns) {
448      int[] newSortedIndex = Enumerable.Range(0, Content.Rows).ToArray();
449      if (sortedColumns.Count() != 0) {
450        rowComparer.SortedIndices = sortedColumns;
451        rowComparer.Matrix = Content;
452        Array.Sort(newSortedIndex, rowComparer);
453      }
454      return newSortedIndex;
455    }
456    private void UpdateSortGlyph() {
457      foreach (DataGridViewColumn col in this.dataGridView.Columns)
458        col.HeaderCell.SortGlyphDirection = SortOrder.None;
459      foreach (KeyValuePair<int, SortOrder> p in sortedColumnIndices)
460        this.dataGridView.Columns[p.Key].HeaderCell.SortGlyphDirection = p.Value;
461    }
462    #endregion
463
464    public int GetRowIndex(int originalIndex) {
465      return virtualRowIndices[originalIndex];
466    }
467
468    public class RowComparer : IComparer<int> {
469      public RowComparer() {
470      }
471
472      private List<KeyValuePair<int, SortOrder>> sortedIndices;
473      public IEnumerable<KeyValuePair<int, SortOrder>> SortedIndices {
474        get { return this.sortedIndices; }
475        set { sortedIndices = new List<KeyValuePair<int, SortOrder>>(value); }
476      }
477      private IStringConvertibleMatrix matrix;
478      public IStringConvertibleMatrix Matrix {
479        get { return this.matrix; }
480        set { this.matrix = value; }
481      }
482
483      public int Compare(int x, int y) {
484        int result = 0;
485        double double1, double2;
486        DateTime dateTime1, dateTime2;
487        TimeSpan timeSpan1, timeSpan2;
488        string string1, string2;
489
490        if (matrix == null)
491          throw new InvalidOperationException("Could not sort IStringConvertibleMatrix if the matrix member is null.");
492        if (sortedIndices == null)
493          return 0;
494
495        foreach (KeyValuePair<int, SortOrder> pair in sortedIndices.Where(p => p.Value != SortOrder.None)) {
496          string1 = matrix.GetValue(x, pair.Key);
497          string2 = matrix.GetValue(y, pair.Key);
498          if (double.TryParse(string1, out double1) && double.TryParse(string2, out double2))
499            result = double1.CompareTo(double2);
500          else if (DateTime.TryParse(string1, out dateTime1) && DateTime.TryParse(string2, out dateTime2))
501            result = dateTime1.CompareTo(dateTime2);
502          else if (TimeSpan.TryParse(string1, out timeSpan1) && TimeSpan.TryParse(string2, out timeSpan2))
503            result = timeSpan1.CompareTo(timeSpan2);
504          else {
505            if (string1 != null)
506              result = string1.CompareTo(string2);
507            else if (string2 != null)
508              result = string2.CompareTo(string1) * -1;
509          }
510          if (pair.Value == SortOrder.Descending)
511            result *= -1;
512          if (result != 0)
513            return result;
514        }
515        return result;
516      }
517    }
518
519    protected virtual void dataGridView_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e) {
520      if (Content == null) return;
521      if (e.Button == MouseButtons.Right && Content.ColumnNames.Count() != 0)
522        contextMenu.Show(MousePosition);
523    }
524    protected virtual void ShowHideColumns_Click(object sender, EventArgs e) {
525      new StringConvertibleMatrixColumnVisibilityDialog(this.dataGridView.Columns.Cast<DataGridViewColumn>()).ShowDialog();
526      columnsTextBox.Text = dataGridView.Columns.GetColumnCount(DataGridViewElementStates.Visible).ToString();
527    }
528
529    private void UpdateVisibilityOfTextBoxes() {
530      rowsTextBox.Visible = columnsTextBox.Visible = showRowsAndColumnsTextBox;
531      rowsLabel.Visible = columnsLabel.Visible = showRowsAndColumnsTextBox;
532      UpdateDataGridViewSizeAndLocation();
533    }
534
535    private void UpdateVisibilityOfStatisticalInformation() {
536      statisticsTextBox.Visible = showStatisticalInformation;
537      UpdateDataGridViewSizeAndLocation();
538    }
539
540    private void UpdateDataGridViewSizeAndLocation() {
541      int headerSize = columnsTextBox.Location.Y + columnsTextBox.Size.Height +
542       columnsTextBox.Margin.Bottom + dataGridView.Margin.Top;
543
544      int offset = showRowsAndColumnsTextBox ? headerSize : 0;
545      dataGridView.Location = new Point(0, offset);
546
547      int statisticsTextBoxHeight = showStatisticalInformation ? statisticsTextBox.Height + statisticsTextBox.Margin.Top + statisticsTextBox.Margin.Bottom : 0;
548      dataGridView.Size = new Size(Size.Width, Size.Height - offset - statisticsTextBoxHeight);
549    }
550
551    protected virtual void dataGridView_SelectionChanged(object sender, EventArgs e) {
552      statisticsTextBox.Text = string.Empty;
553      if (dataGridView.SelectedCells.Count > 1) {
554        List<double> selectedValues = new List<double>();
555        foreach (DataGridViewCell cell in dataGridView.SelectedCells) {
556          double value;
557          if (!double.TryParse(cell.Value.ToString(), out value)) return;
558          selectedValues.Add(value);
559        }
560        if (selectedValues.Count > 1) {
561          statisticsTextBox.Text = CreateStatisticsText(selectedValues);
562        }
563      }
564    }
565
566    protected virtual string CreateStatisticsText(ICollection<double> values) {
567      string stringFormat = "{0,20:0.0000}";
568      int overallCount = values.Count;
569      values = values.Where(x => !double.IsNaN(x)).ToList();
570      if (!values.Any()) {
571        return "";
572      }
573      StringBuilder statisticsText = new StringBuilder();
574      statisticsText.Append("Count: " + values.Count + "    ");
575      statisticsText.Append("Sum: " + string.Format(stringFormat, values.Sum()) + "    ");
576      statisticsText.Append("Min: " + string.Format(stringFormat, values.Min()) + "    ");
577      statisticsText.Append("Max: " + string.Format(stringFormat, values.Max()) + "    ");
578      statisticsText.Append("Average: " + string.Format(stringFormat, values.Average()) + "    ");
579      statisticsText.Append("Standard Deviation: " + string.Format(stringFormat, values.StandardDeviation()) + "    ");
580      if (overallCount > 0)
581        statisticsText.Append("Missing Values: " + string.Format(stringFormat, ((overallCount - values.Count) / (double)overallCount) * 100) + "%    ");
582      return statisticsText.ToString();
583    }
584  }
585}
Note: See TracBrowser for help on using the repository browser.