Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 3729 was 3714, checked in by mkommend, 15 years ago

corrected validating of rows and columns textbox in StringConvertibleMatrixView (ticket #968)

File size: 16.7 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 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.ComponentModel;
24using System.Collections.Generic;
25using System.Drawing;
26using System.Linq;
27using System.Windows.Forms;
28using HeuristicLab.Common;
29using HeuristicLab.MainForm;
30using HeuristicLab.MainForm.WindowsForms;
31
32namespace HeuristicLab.Data.Views {
33  [View("StringConvertibleMatrix View")]
34  [Content(typeof(IStringConvertibleMatrix), true)]
35  public partial class StringConvertibleMatrixView : AsynchronousContentView {
36    protected int[] virtualRowIndizes;
37    private List<KeyValuePair<int, SortOrder>> sortedColumnIndizes;
38    private RowComparer rowComparer;
39
40    public new IStringConvertibleMatrix Content {
41      get { return (IStringConvertibleMatrix)base.Content; }
42      set { base.Content = value; }
43    }
44
45    public override bool ReadOnly {
46      get {
47        if ((Content != null) && Content.ReadOnly) return true;
48        return base.ReadOnly;
49      }
50      set { base.ReadOnly = value; }
51    }
52
53    public StringConvertibleMatrixView() {
54      InitializeComponent();
55      Caption = "StringConvertibleMatrix View";
56      errorProvider.SetIconAlignment(rowsTextBox, ErrorIconAlignment.MiddleLeft);
57      errorProvider.SetIconPadding(rowsTextBox, 2);
58      errorProvider.SetIconAlignment(columnsTextBox, ErrorIconAlignment.MiddleLeft);
59      errorProvider.SetIconPadding(columnsTextBox, 2);
60      sortedColumnIndizes = new List<KeyValuePair<int, SortOrder>>();
61      rowComparer = new RowComparer();
62    }
63
64    protected override void DeregisterContentEvents() {
65      Content.ItemChanged -= new EventHandler<EventArgs<int, int>>(Content_ItemChanged);
66      Content.Reset -= new EventHandler(Content_Reset);
67      Content.ColumnNamesChanged -= new EventHandler(Content_ColumnNamesChanged);
68      Content.RowNamesChanged -= new EventHandler(Content_RowNamesChanged);
69      base.DeregisterContentEvents();
70    }
71    protected override void RegisterContentEvents() {
72      base.RegisterContentEvents();
73      Content.ItemChanged += new EventHandler<EventArgs<int, int>>(Content_ItemChanged);
74      Content.Reset += new EventHandler(Content_Reset);
75      Content.ColumnNamesChanged += new EventHandler(Content_ColumnNamesChanged);
76      Content.RowNamesChanged += new EventHandler(Content_RowNamesChanged);
77    }
78
79    protected override void OnContentChanged() {
80      base.OnContentChanged();
81      if (Content == null) {
82        Caption = "StringConvertibleMatrix View";
83        rowsTextBox.Text = "";
84        columnsTextBox.Text = "";
85        dataGridView.Rows.Clear();
86        dataGridView.Columns.Clear();
87        virtualRowIndizes = new int[0];
88      } else {
89        Caption = "StringConvertibleMatrix (" + Content.GetType().Name + ")";
90        UpdateData();
91      }
92      SetEnabledStateOfControls();
93    }
94    protected override void OnReadOnlyChanged() {
95      base.OnReadOnlyChanged();
96      SetEnabledStateOfControls();
97    }
98    private void SetEnabledStateOfControls() {
99      rowsTextBox.Enabled = Content != null;
100      columnsTextBox.Enabled = Content != null;
101      dataGridView.Enabled = Content != null;
102      rowsTextBox.ReadOnly = ReadOnly;
103      columnsTextBox.ReadOnly = ReadOnly;
104      dataGridView.ReadOnly = ReadOnly;
105    }
106
107    private void UpdateData() {
108      sortedColumnIndizes.Clear();
109      rowsTextBox.Text = Content.Rows.ToString();
110      rowsTextBox.Enabled = true;
111      columnsTextBox.Text = Content.Columns.ToString();
112      columnsTextBox.Enabled = true;
113      virtualRowIndizes = Enumerable.Range(0, Content.Rows).ToArray();
114      //DataGridViews with Rows but no columns are not allowed !
115      if (Content.Rows == 0 && dataGridView.RowCount != Content.Rows && !Content.ReadOnly)
116        Content.Rows = dataGridView.RowCount;
117      else
118        dataGridView.RowCount = Content.Rows;
119      if (Content.Columns == 0 && dataGridView.ColumnCount != Content.Columns && !Content.ReadOnly)
120        Content.Columns = dataGridView.ColumnCount;
121      else
122        dataGridView.ColumnCount = Content.Columns;
123
124      Sort();
125      UpdateRowHeaders();
126      UpdateColumnHeaders();
127      dataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.ColumnHeader);
128      dataGridView.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders);
129      dataGridView.Enabled = true;
130    }
131
132    private void UpdateColumnHeaders() {
133      for (int i = 0; i < Content.Columns; i++) {
134        if (Content.ColumnNames.Count() != 0)
135          dataGridView.Columns[i].HeaderText = Content.ColumnNames.ElementAt(i);
136        else
137          dataGridView.Columns[i].HeaderText = "Column " + (i + 1);
138      }
139      dataGridView.Invalidate();
140    }
141
142    private void UpdateRowHeaders() {
143      for (int i = 0; i < dataGridView.RowCount; i++) {
144        if (Content.RowNames.Count() != 0)
145          dataGridView.Rows[i].HeaderCell.Value = Content.RowNames.ElementAt(virtualRowIndizes[i]);
146        else
147          dataGridView.Rows[i].HeaderCell.Value = "Row " + (i + 1);
148      }
149      dataGridView.Invalidate();
150    }
151
152    private void Content_RowNamesChanged(object sender, EventArgs e) {
153      if (InvokeRequired)
154        Invoke(new EventHandler(Content_RowNamesChanged), sender, e);
155      else
156        UpdateRowHeaders();
157    }
158    private void Content_ColumnNamesChanged(object sender, EventArgs e) {
159      if (InvokeRequired)
160        Invoke(new EventHandler(Content_ColumnNamesChanged), sender, e);
161      else
162        UpdateColumnHeaders();
163    }
164    private void Content_ItemChanged(object sender, EventArgs<int, int> e) {
165      if (InvokeRequired)
166        Invoke(new EventHandler<EventArgs<int, int>>(Content_ItemChanged), sender, e);
167      else
168        dataGridView.InvalidateCell(e.Value2, e.Value);
169    }
170    private void Content_Reset(object sender, EventArgs e) {
171      if (InvokeRequired)
172        Invoke(new EventHandler(Content_Reset), sender, e);
173      else
174        UpdateData();
175    }
176
177    #region TextBox Events
178    private void rowsTextBox_Validating(object sender, CancelEventArgs e) {
179      if (ReadOnly || Locked)
180        return;
181      int i = 0;
182      if (!int.TryParse(rowsTextBox.Text, out i) || (i <= 0)) {
183        e.Cancel = true;
184        errorProvider.SetError(rowsTextBox, "Invalid Number of Rows (Valid values are positive integers larger than 0)");
185        rowsTextBox.SelectAll();
186      }
187    }
188    private void rowsTextBox_Validated(object sender, EventArgs e) {
189      if (!Content.ReadOnly) Content.Rows = int.Parse(rowsTextBox.Text);
190      errorProvider.SetError(rowsTextBox, string.Empty);
191    }
192    private void rowsTextBox_KeyDown(object sender, KeyEventArgs e) {
193      if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
194        rowsLabel.Focus();  // set focus on label to validate data
195      if (e.KeyCode == Keys.Escape) {
196        rowsTextBox.Text = Content.Rows.ToString();
197        rowsLabel.Focus();  // set focus on label to validate data
198      }
199    }
200    private void columnsTextBox_Validating(object sender, CancelEventArgs e) {
201      if (ReadOnly || Locked)
202        return;
203      int i = 0;
204      if (!int.TryParse(columnsTextBox.Text, out i) || (i <= 0)) {
205        e.Cancel = true;
206        errorProvider.SetError(columnsTextBox, "Invalid Number of Columns (Valid values are positive integers larger than 0)");
207        columnsTextBox.SelectAll();
208      }
209    }
210    private void columnsTextBox_Validated(object sender, EventArgs e) {
211      if (!Content.ReadOnly) Content.Columns = int.Parse(columnsTextBox.Text);
212      errorProvider.SetError(columnsTextBox, string.Empty);
213    }
214    private void columnsTextBox_KeyDown(object sender, KeyEventArgs e) {
215      if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
216        columnsLabel.Focus();  // set focus on label to validate data
217      if (e.KeyCode == Keys.Escape) {
218        columnsTextBox.Text = Content.Columns.ToString();
219        columnsLabel.Focus();  // set focus on label to validate data
220      }
221    }
222    #endregion
223
224    #region DataGridView Events
225    private void dataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) {
226      if (!dataGridView.ReadOnly) {
227        string errorMessage;
228        if (!Content.Validate(e.FormattedValue.ToString(), out errorMessage)) {
229          e.Cancel = true;
230          dataGridView.Rows[e.RowIndex].ErrorText = errorMessage;
231        }
232      }
233    }
234    private void dataGridView_CellParsing(object sender, DataGridViewCellParsingEventArgs e) {
235      if (!dataGridView.ReadOnly) {
236        string value = e.Value.ToString();
237        int rowIndex = virtualRowIndizes[e.RowIndex];
238        e.ParsingApplied = Content.SetValue(value, rowIndex, e.ColumnIndex);
239        if (e.ParsingApplied) e.Value = Content.GetValue(rowIndex, e.ColumnIndex);
240      }
241    }
242    private void dataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e) {
243      dataGridView.Rows[e.RowIndex].ErrorText = string.Empty;
244    }
245    private void dataGridView_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e) {
246      if (e.RowIndex < Content.Rows && e.ColumnIndex < Content.Columns) {
247        int rowIndex = virtualRowIndizes[e.RowIndex];
248        e.Value = Content.GetValue(rowIndex, e.ColumnIndex);
249      }
250    }
251    private void dataGridView_Scroll(object sender, ScrollEventArgs e) {
252      UpdateRowHeaders();
253    }
254    private void dataGridView_Resize(object sender, EventArgs e) {
255      UpdateRowHeaders();
256    }
257
258    private void dataGridView_KeyDown(object sender, KeyEventArgs e) {
259      if (!ReadOnly && e.Control && e.KeyCode == Keys.V) { //shortcut for values paste
260        string[,] values = SplitClipboardString(Clipboard.GetText());
261
262        int rowIndex = 0;
263        int columnIndex = 0;
264        if (dataGridView.CurrentCell != null) {
265          rowIndex = dataGridView.CurrentCell.RowIndex;
266          columnIndex = dataGridView.CurrentCell.ColumnIndex;
267        }
268
269        for (int row = 0; row < values.GetLength(1); row++) {
270          if (row + rowIndex >= Content.Rows)
271            Content.Rows = Content.Rows + 1;
272          for (int col = 0; col < values.GetLength(0); col++) {
273            if (col + columnIndex >= Content.Columns)
274              Content.Columns = Content.Columns + 1;
275            Content.SetValue(values[col, row], row + rowIndex, col + columnIndex);
276          }
277        }
278
279        ClearSorting();
280      }
281    }
282
283    private string[,] SplitClipboardString(string clipboardText) {
284      clipboardText = clipboardText.Remove(clipboardText.Length - Environment.NewLine.Length);  //remove last newline constant
285      string[,] values = null;
286      string[] lines = clipboardText.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
287      string[] cells;
288      for (int i = 0; i < lines.Length; i++) {
289        cells = lines[i].Split('\t');
290        if (values == null)
291          values = new string[cells.Length, lines.Length];
292        for (int j = 0; j < cells.Length; j++)
293          values[j, i] = string.IsNullOrEmpty(cells[j]) ? string.Empty : cells[j];
294      }
295      return values;
296    }
297
298    private void dataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
299      if (Content != null) {
300        if (e.Button == MouseButtons.Left && Content.SortableView) {
301          bool addToSortedIndizes = (Control.ModifierKeys & Keys.Control) == Keys.Control;
302          SortOrder newSortOrder = SortOrder.Ascending;
303          if (sortedColumnIndizes.Any(x => x.Key == e.ColumnIndex)) {
304            SortOrder oldSortOrder = sortedColumnIndizes.Where(x => x.Key == e.ColumnIndex).First().Value;
305            int enumLength = Enum.GetValues(typeof(SortOrder)).Length;
306            newSortOrder = oldSortOrder = (SortOrder)Enum.Parse(typeof(SortOrder), ((((int)oldSortOrder) + 1) % enumLength).ToString());
307          }
308
309          if (!addToSortedIndizes)
310            sortedColumnIndizes.Clear();
311
312          if (sortedColumnIndizes.Any(x => x.Key == e.ColumnIndex)) {
313            int sortedIndex = sortedColumnIndizes.FindIndex(x => x.Key == e.ColumnIndex);
314            if (newSortOrder != SortOrder.None)
315              sortedColumnIndizes[sortedIndex] = new KeyValuePair<int, SortOrder>(e.ColumnIndex, newSortOrder);
316            else
317              sortedColumnIndizes.RemoveAt(sortedIndex);
318          } else
319            if (newSortOrder != SortOrder.None)
320              sortedColumnIndizes.Add(new KeyValuePair<int, SortOrder>(e.ColumnIndex, newSortOrder));
321          Sort();
322        } else if (e.Button == MouseButtons.Right) {
323          if (Content.ColumnNames.Count() != 0)
324            contextMenu.Show(MousePosition);
325        }
326      }
327    }
328
329    protected void ClearSorting() {
330      virtualRowIndizes = Enumerable.Range(0, Content.Rows).ToArray();
331      sortedColumnIndizes.Clear();
332      UpdateSortGlyph();
333    }
334
335    private void Sort() {
336      virtualRowIndizes = Sort(sortedColumnIndizes);
337      UpdateSortGlyph();
338      UpdateRowHeaders();
339      dataGridView.Invalidate();
340    }
341    protected virtual int[] Sort(IEnumerable<KeyValuePair<int, SortOrder>> sortedColumns) {
342      int[] newSortedIndex = Enumerable.Range(0, Content.Rows).ToArray();
343      if (sortedColumns.Count() != 0) {
344        rowComparer.SortedIndizes = sortedColumns;
345        rowComparer.Matrix = Content;
346        Array.Sort(newSortedIndex, rowComparer);
347      }
348      return newSortedIndex;
349    }
350    private void UpdateSortGlyph() {
351      foreach (DataGridViewColumn col in this.dataGridView.Columns)
352        col.HeaderCell.SortGlyphDirection = SortOrder.None;
353      foreach (KeyValuePair<int, SortOrder> p in sortedColumnIndizes)
354        this.dataGridView.Columns[p.Key].HeaderCell.SortGlyphDirection = p.Value;
355    }
356    #endregion
357
358    public class RowComparer : IComparer<int> {
359      public RowComparer() {
360      }
361
362      private List<KeyValuePair<int, SortOrder>> sortedIndizes;
363      public IEnumerable<KeyValuePair<int, SortOrder>> SortedIndizes {
364        get { return this.sortedIndizes; }
365        set { sortedIndizes = new List<KeyValuePair<int, SortOrder>>(value); }
366      }
367      private IStringConvertibleMatrix matrix;
368      public IStringConvertibleMatrix Matrix {
369        get { return this.matrix; }
370        set { this.matrix = value; }
371      }
372
373      public int Compare(int x, int y) {
374        int result = 0;
375        double double1, double2;
376        DateTime dateTime1, dateTime2;
377        TimeSpan timeSpan1, timeSpan2;
378        string string1, string2;
379
380        if (matrix == null)
381          throw new InvalidOperationException("Could not sort IStringConvertibleMatrix if the matrix member is null.");
382        if (sortedIndizes == null)
383          return 0;
384
385        foreach (KeyValuePair<int, SortOrder> pair in sortedIndizes.Where(p => p.Value != SortOrder.None)) {
386          string1 = matrix.GetValue(x, pair.Key);
387          string2 = matrix.GetValue(y, pair.Key);
388          if (double.TryParse(string1, out double1) && double.TryParse(string2, out double2))
389            result = double1.CompareTo(double2);
390          else if (DateTime.TryParse(string1, out dateTime1) && DateTime.TryParse(string2, out dateTime2))
391            result = dateTime1.CompareTo(dateTime2);
392          else if (TimeSpan.TryParse(string1, out timeSpan1) && TimeSpan.TryParse(string2, out timeSpan2))
393            result = timeSpan1.CompareTo(timeSpan2);
394          else {
395            if (string1 != null)
396              result = string1.CompareTo(string2);
397            else if (string2 != null)
398              result = string2.CompareTo(string1) * -1;
399          }
400          if (pair.Value == SortOrder.Descending)
401            result *= -1;
402          if (result != 0)
403            return result;
404        }
405        return result;
406      }
407    }
408
409    private void ShowHideColumns_Click(object sender, EventArgs e) {
410      new ColumnsVisibilityDialog(this.dataGridView.Columns.Cast<DataGridViewColumn>()).ShowDialog();
411    }
412  }
413}
Note: See TracBrowser for help on using the repository browser.