Free cookie consent management tool by TermsFeed Policy Generator

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

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

added null checks for content in CellValidatingEvent of StringConvertibleArray and -MatrixView (ticket #968)

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