Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 13820 was 13570, checked in by mkommend, 9 years ago

#2568: Changed access modifiers of UpdateRow/ColumnHeader in the StringConvertibleMatrix/ArrayView to public.

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