source: branches/ImprovingStringConvertibleMatrix/HeuristicLab.Data.Views/3.3/StringConvertibleMatrixView.cs @ 9306

Last change on this file since 9306 was 9306, checked in by sforsten, 8 years ago

#2018:

  • renamed the structs and methods in IStringConvertibleMatrix
  • added MatrixValuesChangedEventArgs in IStringConvertibleMatrix
  • added methods SetValues(MatrixValues<T>) in ValueTypeMatrix
  • fixed bugs in StringConvertibleMatrixView: DataGridView has now at least one column and dataGridView_CellValidating does not set e.Cancel to true anymore.
File size: 23.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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    private 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.ItemsChanged -= new EventHandler<MatrixValuesChangedEventArgs>(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.ItemsChanged += new EventHandler<MatrixValuesChangedEventArgs>(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
112        UpdateData();
113    }
114
115    protected override void SetEnabledStateOfControls() {
116      base.SetEnabledStateOfControls();
117      rowsTextBox.Enabled = Content != null;
118      columnsTextBox.Enabled = Content != null;
119      dataGridView.Enabled = Content != null;
120      rowsTextBox.ReadOnly = ReadOnly;
121      columnsTextBox.ReadOnly = ReadOnly;
122      dataGridView.ReadOnly = ReadOnly;
123    }
124
125    private void UpdateData() {
126      rowsTextBox.Text = Content.Rows.ToString();
127      rowsTextBox.Enabled = true;
128      columnsTextBox.Text = Content.Columns.ToString();
129      columnsTextBox.Enabled = true;
130      virtualRowIndices = Enumerable.Range(0, Content.Rows).ToArray();
131
132      //dataGridView.RowCount = 0;
133
134      if (Content.Columns == 0) {
135        Content.Columns = 1;
136      } else {
137        DataGridViewColumn[] columns = new DataGridViewColumn[Content.Columns];
138        for (int i = 0; i < columns.Length; ++i) {
139          var column = new DataGridViewTextBoxColumn();
140          column.FillWeight = 1;
141          columns[i] = column;
142        }
143        dataGridView.Columns.Clear();
144        dataGridView.Columns.AddRange(columns);
145      }
146
147      dataGridView.RowCount = Content.Rows;
148
149      ClearSorting();
150      UpdateColumnHeaders();
151      UpdateRowHeaders();
152
153      dataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.ColumnHeader);
154      dataGridView.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders);
155      dataGridView.Enabled = true;
156    }
157
158    protected virtual void UpdateColumnHeaders() {
159      HashSet<string> invisibleColumnNames = new HashSet<string>(dataGridView.Columns.OfType<DataGridViewColumn>()
160      .Where(c => !c.Visible && !string.IsNullOrEmpty(c.HeaderText)).Select(c => c.HeaderText));
161
162      for (int i = 0; i < dataGridView.ColumnCount; i++) {
163        if (i < Content.ColumnNames.Count())
164          dataGridView.Columns[i].HeaderText = Content.ColumnNames.ElementAt(i);
165        else
166          dataGridView.Columns[i].HeaderText = "Column " + (i + 1);
167        dataGridView.Columns[i].Visible = !invisibleColumnNames.Contains(dataGridView.Columns[i].HeaderText);
168      }
169    }
170    protected virtual void UpdateRowHeaders() {
171      int index = dataGridView.FirstDisplayedScrollingRowIndex;
172      if (index == -1) index = 0;
173      int updatedRows = 0;
174      int count = dataGridView.DisplayedRowCount(true);
175
176      while (updatedRows < count) {
177        if (virtualRowIndices[index] < Content.RowNames.Count())
178          dataGridView.Rows[index].HeaderCell.Value = Content.RowNames.ElementAt(virtualRowIndices[index]);
179        else
180          dataGridView.Rows[index].HeaderCell.Value = "Row " + (index + 1);
181        if (dataGridView.Rows[index].Visible)
182          updatedRows++;
183        index++;
184      }
185    }
186
187    private void Content_RowNamesChanged(object sender, EventArgs e) {
188      if (InvokeRequired)
189        Invoke(new EventHandler(Content_RowNamesChanged), sender, e);
190      else
191        UpdateRowHeaders();
192    }
193    private void Content_ColumnNamesChanged(object sender, EventArgs e) {
194      if (InvokeRequired)
195        Invoke(new EventHandler(Content_ColumnNamesChanged), sender, e);
196      else
197        UpdateColumnHeaders();
198    }
199    private void Content_ItemChanged(object sender, MatrixValuesChangedEventArgs e) {
200      if (InvokeRequired)
201        Invoke(new EventHandler<MatrixValuesChangedEventArgs>(Content_ItemChanged), sender, e);
202      else {
203        foreach (var pos in e.Value) {
204          dataGridView.InvalidateCell(pos.Column, pos.Row);
205        }
206      }
207    }
208    private void Content_Reset(object sender, EventArgs e) {
209      if (InvokeRequired)
210        Invoke(new EventHandler(Content_Reset), sender, e);
211      else
212        UpdateData();
213    }
214
215    #region TextBox Events
216    private void rowsTextBox_Validating(object sender, CancelEventArgs e) {
217      if (ReadOnly || Locked)
218        return;
219      int i = 0;
220      if (!int.TryParse(rowsTextBox.Text, out i) || (i <= 0)) {
221        e.Cancel = true;
222        errorProvider.SetError(rowsTextBox, "Invalid Number of Rows (Valid values are positive integers larger than 0)");
223        rowsTextBox.SelectAll();
224      }
225    }
226    private void rowsTextBox_Validated(object sender, EventArgs e) {
227      if (!Content.ReadOnly) Content.Rows = int.Parse(rowsTextBox.Text);
228      errorProvider.SetError(rowsTextBox, string.Empty);
229    }
230    private void rowsTextBox_KeyDown(object sender, KeyEventArgs e) {
231      if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
232        rowsLabel.Focus();  // set focus on label to validate data
233      if (e.KeyCode == Keys.Escape) {
234        rowsTextBox.Text = Content.Rows.ToString();
235        rowsLabel.Focus();  // set focus on label to validate data
236      }
237    }
238    private void columnsTextBox_Validating(object sender, CancelEventArgs e) {
239      if (ReadOnly || Locked)
240        return;
241      int i = 0;
242      if (!int.TryParse(columnsTextBox.Text, out i) || (i <= 0)) {
243        e.Cancel = true;
244        errorProvider.SetError(columnsTextBox, "Invalid Number of Columns (Valid values are positive integers larger than 0)");
245        columnsTextBox.SelectAll();
246      }
247    }
248    private void columnsTextBox_Validated(object sender, EventArgs e) {
249      if (!Content.ReadOnly) Content.Columns = int.Parse(columnsTextBox.Text);
250      errorProvider.SetError(columnsTextBox, string.Empty);
251    }
252    private void columnsTextBox_KeyDown(object sender, KeyEventArgs e) {
253      if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
254        columnsLabel.Focus();  // set focus on label to validate data
255      if (e.KeyCode == Keys.Escape) {
256        columnsTextBox.Text = Content.Columns.ToString();
257        columnsLabel.Focus();  // set focus on label to validate data
258      }
259    }
260    #endregion
261
262    #region DataGridView Events
263    private void dataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) {
264      if (!dataGridView.ReadOnly) {
265        string errorMessage;
266        if (Content != null && !Content.Validate(e.FormattedValue.ToString(), out errorMessage)) {
267          //e.Cancel = true;
268          dataGridView.Rows[e.RowIndex].ErrorText = errorMessage;
269        }
270      }
271    }
272    private void dataGridView_CellParsing(object sender, DataGridViewCellParsingEventArgs e) {
273      if (!dataGridView.ReadOnly) {
274        string value = e.Value.ToString();
275        int rowIndex = virtualRowIndices[e.RowIndex];
276        e.ParsingApplied = Content.SetValue(value, rowIndex, e.ColumnIndex);
277        if (e.ParsingApplied) e.Value = Content.GetValue(rowIndex, e.ColumnIndex);
278      }
279    }
280    private void dataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e) {
281      dataGridView.Rows[e.RowIndex].ErrorText = string.Empty;
282    }
283    private void dataGridView_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e) {
284      if (Content != null && e.RowIndex < Content.Rows && e.ColumnIndex < Content.Columns) {
285        int rowIndex = virtualRowIndices[e.RowIndex];
286        e.Value = Content.GetValue(rowIndex, e.ColumnIndex);
287      }
288    }
289
290    private void dataGridView_Scroll(object sender, System.Windows.Forms.ScrollEventArgs e) {
291      this.UpdateRowHeaders();
292    }
293    private void dataGridView_Resize(object sender, EventArgs e) {
294      this.UpdateRowHeaders();
295    }
296
297    private void dataGridView_KeyDown(object sender, KeyEventArgs e) {
298      if (!ReadOnly && e.Control && e.KeyCode == Keys.V)
299        PasteValuesToDataGridView();
300      else if (e.Control && e.KeyCode == Keys.C)
301        CopyValuesFromDataGridView();
302    }
303
304    private void CopyValuesFromDataGridView() {
305      if (dataGridView.SelectedCells.Count == 0) return;
306      StringBuilder s = new StringBuilder();
307      int minRowIndex = dataGridView.SelectedCells[0].RowIndex;
308      int maxRowIndex = dataGridView.SelectedCells[dataGridView.SelectedCells.Count - 1].RowIndex;
309      int minColIndex = dataGridView.SelectedCells[0].ColumnIndex;
310      int maxColIndex = dataGridView.SelectedCells[dataGridView.SelectedCells.Count - 1].ColumnIndex;
311
312      if (minRowIndex > maxRowIndex) {
313        int temp = minRowIndex;
314        minRowIndex = maxRowIndex;
315        maxRowIndex = temp;
316      }
317      if (minColIndex > maxColIndex) {
318        int temp = minColIndex;
319        minColIndex = maxColIndex;
320        maxColIndex = temp;
321      }
322
323      bool addRowNames = dataGridView.AreAllCellsSelected(false) && Content.RowNames.Count() > 0;
324      bool addColumnNames = dataGridView.AreAllCellsSelected(false) && Content.ColumnNames.Count() > 0;
325
326      //add colum names
327      if (addColumnNames) {
328        if (addRowNames)
329          s.Append('\t');
330
331        DataGridViewColumn column = dataGridView.Columns.GetFirstColumn(DataGridViewElementStates.Visible);
332        while (column != null) {
333          s.Append(column.HeaderText);
334          s.Append('\t');
335          column = dataGridView.Columns.GetNextColumn(column, DataGridViewElementStates.Visible, DataGridViewElementStates.None);
336        }
337        s.Remove(s.Length - 1, 1); //remove last tab
338        s.Append(Environment.NewLine);
339      }
340
341      for (int i = minRowIndex; i <= maxRowIndex; i++) {
342        int rowIndex = this.virtualRowIndices[i];
343        if (addRowNames) {
344          s.Append(Content.RowNames.ElementAt(rowIndex));
345          s.Append('\t');
346        }
347
348        DataGridViewColumn column = dataGridView.Columns.GetFirstColumn(DataGridViewElementStates.Visible);
349        while (column != null) {
350          DataGridViewCell cell = dataGridView[column.Index, i];
351          if (cell.Selected) {
352            s.Append(Content.GetValue(rowIndex, column.Index));
353            s.Append('\t');
354          }
355
356          column = dataGridView.Columns.GetNextColumn(column, DataGridViewElementStates.Visible, DataGridViewElementStates.None);
357        }
358        s.Remove(s.Length - 1, 1); //remove last tab
359        s.Append(Environment.NewLine);
360      }
361      Clipboard.SetText(s.ToString());
362    }
363
364    private void PasteValuesToDataGridView() {
365      string[,] values = SplitClipboardString(Clipboard.GetText());
366      int rowIndex = 0;
367      int columnIndex = 0;
368      if (dataGridView.CurrentCell != null) {
369        rowIndex = dataGridView.CurrentCell.RowIndex;
370        columnIndex = dataGridView.CurrentCell.ColumnIndex;
371      }
372      if (Content.Rows < values.GetLength(1) + rowIndex) Content.Rows = values.GetLength(1) + rowIndex;
373      if (Content.Columns < values.GetLength(0) + columnIndex) Content.Columns = values.GetLength(0) + columnIndex;
374
375      List<MatrixValue<string>> setValues = new List<MatrixValue<string>>(values.GetLength(0) * values.GetLength(1));
376      for (int row = 0; row < values.GetLength(1); row++) {
377        for (int col = 0; col < values.GetLength(0); col++) {
378          setValues.Add(new MatrixValue<string>(new MatrixPosition(row + rowIndex, col + columnIndex), values[col, row]));
379        }
380      }
381      Content.SetValues(setValues);
382      ClearSorting();
383    }
384    private string[,] SplitClipboardString(string clipboardText) {
385      if (clipboardText.EndsWith(Environment.NewLine))
386        clipboardText = clipboardText.Remove(clipboardText.Length - Environment.NewLine.Length);  //remove last newline constant
387      string[,] values = null;
388      string[] lines = clipboardText.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
389      string[] cells;
390      for (int i = 0; i < lines.Length; i++) {
391        cells = lines[i].Split('\t');
392        if (values == null)
393          values = new string[cells.Length, lines.Length];
394        for (int j = 0; j < cells.Length; j++)
395          values[j, i] = string.IsNullOrEmpty(cells[j]) ? string.Empty : cells[j];
396      }
397      return values;
398    }
399
400    private void dataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
401      if (Content != null) {
402        if (e.Button == MouseButtons.Left && Content.SortableView) {
403          bool addToSortedIndices = (Control.ModifierKeys & Keys.Control) == Keys.Control;
404          SortOrder newSortOrder = SortOrder.Ascending;
405          if (sortedColumnIndices.Any(x => x.Key == e.ColumnIndex)) {
406            SortOrder oldSortOrder = sortedColumnIndices.Where(x => x.Key == e.ColumnIndex).First().Value;
407            int enumLength = Enum.GetValues(typeof(SortOrder)).Length;
408            newSortOrder = oldSortOrder = (SortOrder)Enum.Parse(typeof(SortOrder), ((((int)oldSortOrder) + 1) % enumLength).ToString());
409          }
410
411          if (!addToSortedIndices)
412            sortedColumnIndices.Clear();
413
414          if (sortedColumnIndices.Any(x => x.Key == e.ColumnIndex)) {
415            int sortedIndex = sortedColumnIndices.FindIndex(x => x.Key == e.ColumnIndex);
416            if (newSortOrder != SortOrder.None)
417              sortedColumnIndices[sortedIndex] = new KeyValuePair<int, SortOrder>(e.ColumnIndex, newSortOrder);
418            else
419              sortedColumnIndices.RemoveAt(sortedIndex);
420          } else
421            if (newSortOrder != SortOrder.None)
422              sortedColumnIndices.Add(new KeyValuePair<int, SortOrder>(e.ColumnIndex, newSortOrder));
423          Sort();
424        }
425      }
426    }
427
428    protected virtual void ClearSorting() {
429      virtualRowIndices = Enumerable.Range(0, Content.Rows).ToArray();
430      sortedColumnIndices.Clear();
431      UpdateSortGlyph();
432    }
433
434    private void Sort() {
435      virtualRowIndices = Sort(sortedColumnIndices);
436      UpdateSortGlyph();
437      UpdateRowHeaders();
438      dataGridView.Invalidate();
439    }
440    protected virtual int[] Sort(IEnumerable<KeyValuePair<int, SortOrder>> sortedColumns) {
441      int[] newSortedIndex = Enumerable.Range(0, Content.Rows).ToArray();
442      if (sortedColumns.Count() != 0) {
443        rowComparer.SortedIndices = sortedColumns;
444        rowComparer.Matrix = Content;
445        Array.Sort(newSortedIndex, rowComparer);
446      }
447      return newSortedIndex;
448    }
449    private void UpdateSortGlyph() {
450      foreach (DataGridViewColumn col in this.dataGridView.Columns)
451        col.HeaderCell.SortGlyphDirection = SortOrder.None;
452      foreach (KeyValuePair<int, SortOrder> p in sortedColumnIndices)
453        this.dataGridView.Columns[p.Key].HeaderCell.SortGlyphDirection = p.Value;
454    }
455    #endregion
456
457    public class RowComparer : IComparer<int> {
458      public RowComparer() {
459      }
460
461      private List<KeyValuePair<int, SortOrder>> sortedIndices;
462      public IEnumerable<KeyValuePair<int, SortOrder>> SortedIndices {
463        get { return this.sortedIndices; }
464        set { sortedIndices = new List<KeyValuePair<int, SortOrder>>(value); }
465      }
466      private IStringConvertibleMatrix matrix;
467      public IStringConvertibleMatrix Matrix {
468        get { return this.matrix; }
469        set { this.matrix = value; }
470      }
471
472      public int Compare(int x, int y) {
473        int result = 0;
474        double double1, double2;
475        DateTime dateTime1, dateTime2;
476        TimeSpan timeSpan1, timeSpan2;
477        string string1, string2;
478
479        if (matrix == null)
480          throw new InvalidOperationException("Could not sort IStringConvertibleMatrix if the matrix member is null.");
481        if (sortedIndices == null)
482          return 0;
483
484        foreach (KeyValuePair<int, SortOrder> pair in sortedIndices.Where(p => p.Value != SortOrder.None)) {
485          string1 = matrix.GetValue(x, pair.Key);
486          string2 = matrix.GetValue(y, pair.Key);
487          if (double.TryParse(string1, out double1) && double.TryParse(string2, out double2))
488            result = double1.CompareTo(double2);
489          else if (DateTime.TryParse(string1, out dateTime1) && DateTime.TryParse(string2, out dateTime2))
490            result = dateTime1.CompareTo(dateTime2);
491          else if (TimeSpan.TryParse(string1, out timeSpan1) && TimeSpan.TryParse(string2, out timeSpan2))
492            result = timeSpan1.CompareTo(timeSpan2);
493          else {
494            if (string1 != null)
495              result = string1.CompareTo(string2);
496            else if (string2 != null)
497              result = string2.CompareTo(string1) * -1;
498          }
499          if (pair.Value == SortOrder.Descending)
500            result *= -1;
501          if (result != 0)
502            return result;
503        }
504        return result;
505      }
506    }
507
508    private void dataGridView_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e) {
509      if (Content == null) return;
510      if (e.Button == MouseButtons.Right && Content.ColumnNames.Count() != 0)
511        contextMenu.Show(MousePosition);
512    }
513    protected virtual void ShowHideColumns_Click(object sender, EventArgs e) {
514      new StringConvertibleMatrixColumnVisibilityDialog(this.dataGridView.Columns.Cast<DataGridViewColumn>()).ShowDialog();
515    }
516
517    private void UpdateVisibilityOfTextBoxes() {
518      rowsTextBox.Visible = columnsTextBox.Visible = showRowsAndColumnsTextBox;
519      rowsLabel.Visible = columnsLabel.Visible = showRowsAndColumnsTextBox;
520      UpdateDataGridViewSizeAndLocation();
521    }
522
523    private void UpdateVisibilityOfStatisticalInformation() {
524      statisticsTextBox.Visible = showStatisticalInformation;
525      UpdateDataGridViewSizeAndLocation();
526    }
527
528    private void UpdateDataGridViewSizeAndLocation() {
529      int headerSize = columnsTextBox.Location.Y + columnsTextBox.Size.Height +
530       columnsTextBox.Margin.Bottom + dataGridView.Margin.Top;
531
532      int offset = showRowsAndColumnsTextBox ? headerSize : 0;
533      dataGridView.Location = new Point(0, offset);
534
535      int statisticsTextBoxHeight = showStatisticalInformation ? statisticsTextBox.Height + statisticsTextBox.Margin.Top + statisticsTextBox.Margin.Bottom : 0;
536      dataGridView.Size = new Size(Size.Width, Size.Height - offset - statisticsTextBoxHeight);
537    }
538
539    private void dataGridView_SelectionChanged(object sender, EventArgs e) {
540      string stringFormat = "{0,20:0.0000}";
541      statisticsTextBox.Text = string.Empty;
542      if (dataGridView.SelectedCells.Count > 1) {
543        List<double> selectedValues = new List<double>();
544        foreach (DataGridViewCell cell in dataGridView.SelectedCells) {
545          double value;
546          if (cell.Value == null || !double.TryParse(cell.Value.ToString(), out value)) return;
547          selectedValues.Add(value);
548        }
549        if (selectedValues.Count > 1) {
550          StringBuilder labelText = new StringBuilder();
551          labelText.Append("Count: " + string.Format(stringFormat, selectedValues.Count) + "    ");
552          labelText.Append("Sum: " + string.Format(stringFormat, selectedValues.Sum()) + "    ");
553          labelText.Append("Min: " + string.Format(stringFormat, selectedValues.Min()) + "    ");
554          labelText.Append("Max: " + string.Format(stringFormat, selectedValues.Max()) + "    ");
555          labelText.Append("Average: " + string.Format(stringFormat, selectedValues.Average()) + "    ");
556          labelText.Append("Standard Deviation: " + string.Format(stringFormat, selectedValues.StandardDeviation()) + "    ");
557
558          statisticsTextBox.Text = labelText.ToString();
559        }
560      }
561    }
562  }
563}
Note: See TracBrowser for help on using the repository browser.