Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 10691 was 10691, checked in by mleitner, 10 years ago

Autosize table columns and keep selection on refresh

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