Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 9426 was 9422, checked in by mkommend, 12 years ago

#2018: Updated StringConvertibleMatrixView branch with the latest trunk changes.

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