Free cookie consent management tool by TermsFeed Policy Generator

source: branches/MemPRAlgorithm/HeuristicLab.Data.Views/3.3/StringConvertibleMatrixView.cs @ 15694

Last change on this file since 15694 was 14562, checked in by abeham, 8 years ago

#2701: Updated branch to trunk

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