Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ImprovingStringConvertibleMatrix/HeuristicLab.Data.Views/3.3/StringConvertibleMatrixView.cs @ 9286

Last change on this file since 9286 was 9286, checked in by sforsten, 11 years ago

#2018:

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