Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Data.Views/3.3/StringConvertibleMatrixView.cs @ 4798

Last change on this file since 4798 was 4798, checked in by mkommend, 14 years ago

Fixed updating of StringConvertibleMatrixView if the number of columns gets changed (ticket #1266).

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