source: branches/DataPreprocessing/HeuristicLab.DataPreprocessing.Views/3.3/CopyOfStringConvertibleMatrixView.cs @ 10583

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