Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 3335 was 3335, checked in by mkommend, 13 years ago

fixed bugs in IStringConvertibleMatrixView (ticket #968)

File size: 14.0 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    public new IStringConvertibleMatrix Content {
37      get { return (IStringConvertibleMatrix)base.Content; }
38      set { base.Content = value; }
39    }
40
41    private int[] virtualRowIndizes;
42    private List<KeyValuePair<int, SortOrder>> sortedColumnIndizes;
43    RowComparer rowComparer;
44
45    public StringConvertibleMatrixView() {
46      InitializeComponent();
47      Caption = "StringConvertibleMatrix View";
48      errorProvider.SetIconAlignment(rowsTextBox, ErrorIconAlignment.MiddleLeft);
49      errorProvider.SetIconPadding(rowsTextBox, 2);
50      errorProvider.SetIconAlignment(columnsTextBox, ErrorIconAlignment.MiddleLeft);
51      errorProvider.SetIconPadding(columnsTextBox, 2);
52      sortedColumnIndizes = new List<KeyValuePair<int, SortOrder>>();
53      rowComparer = new RowComparer();
54    }
55    public StringConvertibleMatrixView(IStringConvertibleMatrix content)
56      : this() {
57      Content = content;
58    }
59
60    protected override void DeregisterContentEvents() {
61      Content.ItemChanged -= new EventHandler<EventArgs<int, int>>(Content_ItemChanged);
62      Content.Reset -= new EventHandler(Content_Reset);
63      Content.ColumnNamesChanged -= new EventHandler(Content_ColumnNamesChanged);
64      Content.RowNamesChanged -= new EventHandler(Content_RowNamesChanged);
65      Content.ReadOnlyViewChanged -= new EventHandler(Content_ReadOnlyViewChanged);
66      base.DeregisterContentEvents();
67    }
68
69    protected override void RegisterContentEvents() {
70      base.RegisterContentEvents();
71      Content.ItemChanged += new EventHandler<EventArgs<int, int>>(Content_ItemChanged);
72      Content.Reset += new EventHandler(Content_Reset);
73      Content.ColumnNamesChanged += new EventHandler(Content_ColumnNamesChanged);
74      Content.RowNamesChanged += new EventHandler(Content_RowNamesChanged);
75      Content.ReadOnlyViewChanged += new EventHandler(Content_ReadOnlyViewChanged);
76    }
77
78
79    protected override void OnContentChanged() {
80      base.OnContentChanged();
81      if (Content == null) {
82        Caption = "StringConvertibleMatrix View";
83        rowsTextBox.Text = "";
84        rowsTextBox.Enabled = false;
85        columnsTextBox.Text = "";
86        columnsTextBox.Enabled = false;
87        dataGridView.Rows.Clear();
88        dataGridView.Columns.Clear();
89        dataGridView.Enabled = false;
90        virtualRowIndizes = new int[0];
91      } else {
92        Caption = "StringConvertibleMatrix (" + Content.GetType().Name + ")";
93        UpdateReadOnlyControls();
94        UpdateData();
95      }
96    }
97
98    private void UpdateData() {
99      sortedColumnIndizes.Clear();
100      Sort();
101      rowsTextBox.Text = Content.Rows.ToString();
102      rowsTextBox.Enabled = true;
103      columnsTextBox.Text = Content.Columns.ToString();
104      columnsTextBox.Enabled = true;
105      virtualRowIndizes = Enumerable.Range(0, Content.Rows).ToArray();
106      //DataGridViews with Rows but no columns are not allowed !
107      if (Content.Rows == 0 && dataGridView.RowCount != Content.Rows)
108        Content.Rows = dataGridView.RowCount;
109      else
110        dataGridView.RowCount = Content.Rows;
111      if (Content.Columns == 0 && dataGridView.ColumnCount != Content.Columns)
112        Content.Columns = dataGridView.ColumnCount;
113      else
114        dataGridView.ColumnCount = Content.Columns;
115      UpdateRowHeaders();
116      UpdateColumnHeaders();
117      dataGridView.Enabled = true;
118    }
119
120    private void UpdateColumnHeaders() {
121      for (int i = 0; i < Content.Columns; i++) {
122        if (Content.ColumnNames.Count() != 0)
123          dataGridView.Columns[i].HeaderText = Content.ColumnNames.ElementAt(i);
124        else
125          dataGridView.Columns[i].HeaderText = "Column " + i;
126      }
127      dataGridView.Invalidate();
128    }
129
130    private void UpdateRowHeaders() {
131      for (int i = dataGridView.FirstDisplayedScrollingRowIndex; i < dataGridView.FirstDisplayedScrollingRowIndex + dataGridView.DisplayedRowCount(true); i++) {
132        if (Content.RowNames.Count() != 0)
133          dataGridView.Rows[i].HeaderCell.Value = Content.RowNames.ElementAt(i);
134        else
135          dataGridView.Rows[i].HeaderCell.Value = i.ToString();
136      }
137      dataGridView.Invalidate();
138    }
139
140    private void UpdateReadOnlyControls() {
141      dataGridView.ReadOnly = Content.ReadOnlyView;
142      rowsTextBox.ReadOnly = Content.ReadOnlyView;
143      columnsTextBox.ReadOnly = Content.ReadOnlyView;
144    }
145
146    private void Content_RowNamesChanged(object sender, EventArgs e) {
147      if (InvokeRequired)
148        Invoke(new EventHandler(Content_RowNamesChanged), sender, e);
149      else
150        UpdateRowHeaders();
151    }
152    private void Content_ColumnNamesChanged(object sender, EventArgs e) {
153      if (InvokeRequired)
154        Invoke(new EventHandler(Content_ColumnNamesChanged), sender, e);
155      else
156        UpdateColumnHeaders();
157    }
158    private void Content_ItemChanged(object sender, EventArgs<int, int> e) {
159      if (InvokeRequired)
160        Invoke(new EventHandler<EventArgs<int, int>>(Content_ItemChanged), sender, e);
161      else
162        dataGridView.InvalidateCell(e.Value2, e.Value);
163    }
164    private void Content_Reset(object sender, EventArgs e) {
165      if (InvokeRequired)
166        Invoke(new EventHandler(Content_Reset), sender, e);
167      else
168        UpdateData();
169    }
170
171    private void Content_ReadOnlyViewChanged(object sender, EventArgs e) {
172      if (InvokeRequired)
173        Invoke(new EventHandler(Content_ReadOnlyViewChanged), sender, e);
174      else
175        UpdateReadOnlyControls();
176    }
177
178    #region TextBox Events
179    private void rowsTextBox_Validating(object sender, CancelEventArgs e) {
180      int i = 0;
181      if (!int.TryParse(rowsTextBox.Text, out i) || (i <= 0)) {
182        e.Cancel = true;
183        errorProvider.SetError(rowsTextBox, "Invalid Number of Rows (Valid values are positive integers larger than 0)");
184        rowsTextBox.SelectAll();
185      }
186    }
187    private void rowsTextBox_Validated(object sender, EventArgs e) {
188      int textBoxValue = int.Parse(rowsTextBox.Text);
189      if (textBoxValue != Content.Rows)
190        Content.Rows = textBoxValue;
191      errorProvider.SetError(rowsTextBox, string.Empty);
192    }
193    private void rowsTextBox_KeyDown(object sender, KeyEventArgs e) {
194      if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
195        rowsLabel.Focus();  // set focus on label to validate data
196      if (e.KeyCode == Keys.Escape) {
197        rowsTextBox.Text = Content.Rows.ToString();
198        rowsLabel.Focus();  // set focus on label to validate data
199      }
200    }
201    private void columnsTextBox_Validating(object sender, CancelEventArgs e) {
202      int i = 0;
203      if (!int.TryParse(columnsTextBox.Text, out i) || (i <= 0)) {
204        e.Cancel = true;
205        errorProvider.SetError(columnsTextBox, "Invalid Number of Columns (Valid values are positive integers larger than 0)");
206        columnsTextBox.SelectAll();
207      }
208    }
209    private void columnsTextBox_Validated(object sender, EventArgs e) {
210      int textBoxValue = int.Parse(columnsTextBox.Text);
211      if (textBoxValue != Content.Columns)
212        Content.Columns = textBoxValue;
213      errorProvider.SetError(columnsTextBox, string.Empty);
214    }
215    private void columnsTextBox_KeyDown(object sender, KeyEventArgs e) {
216      if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
217        columnsLabel.Focus();  // set focus on label to validate data
218      if (e.KeyCode == Keys.Escape) {
219        columnsTextBox.Text = Content.Columns.ToString();
220        columnsLabel.Focus();  // set focus on label to validate data
221      }
222    }
223    #endregion
224
225    #region DataGridView Events
226    private void dataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) {
227      if (!dataGridView.ReadOnly) {
228        string errorMessage;
229        if (!Content.Validate(e.FormattedValue.ToString(), out errorMessage)) {
230          e.Cancel = true;
231          dataGridView.Rows[e.RowIndex].ErrorText = errorMessage;
232        }
233      }
234    }
235    private void dataGridView_CellParsing(object sender, DataGridViewCellParsingEventArgs e) {
236      if (!dataGridView.ReadOnly) {
237        string value = e.Value.ToString();
238        int rowIndex = virtualRowIndizes[e.RowIndex];
239        e.ParsingApplied = Content.SetValue(value, rowIndex, e.ColumnIndex);
240        if (e.ParsingApplied) e.Value = Content.GetValue(rowIndex, e.ColumnIndex);
241      }
242    }
243    private void dataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e) {
244      dataGridView.Rows[e.RowIndex].ErrorText = string.Empty;
245    }
246    private void dataGridView_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e) {
247      int rowIndex = virtualRowIndizes[e.RowIndex];
248      if (e.RowIndex < Content.Rows && e.ColumnIndex < Content.Columns)
249        e.Value = Content.GetValue(rowIndex, e.ColumnIndex);
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_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
259      if (Content != null) {
260        if (e.Button == MouseButtons.Left && Content.SortableView) {
261          bool addToSortedIndizes = (Control.ModifierKeys & Keys.Control) == Keys.Control;
262          SortOrder newSortOrder = SortOrder.Ascending;
263          if (sortedColumnIndizes.Any(x => x.Key == e.ColumnIndex)) {
264            SortOrder oldSortOrder = sortedColumnIndizes.Where(x => x.Key == e.ColumnIndex).First().Value;
265            int enumLength = Enum.GetValues(typeof(SortOrder)).Length;
266            newSortOrder = oldSortOrder = (SortOrder)Enum.Parse(typeof(SortOrder), ((((int)oldSortOrder) + 1) % enumLength).ToString());
267          }
268
269          if (!addToSortedIndizes)
270            sortedColumnIndizes.Clear();
271
272          if (sortedColumnIndizes.Any(x => x.Key == e.ColumnIndex)) {
273            int sortedIndex = sortedColumnIndizes.FindIndex(x => x.Key == e.ColumnIndex);
274            if (newSortOrder != SortOrder.None)
275              sortedColumnIndizes[sortedIndex] = new KeyValuePair<int, SortOrder>(e.ColumnIndex, newSortOrder);
276            else
277              sortedColumnIndizes.RemoveAt(sortedIndex);
278          } else
279            if (newSortOrder != SortOrder.None)
280              sortedColumnIndizes.Add(new KeyValuePair<int, SortOrder>(e.ColumnIndex, newSortOrder));
281          Sort();
282        } else if (e.Button == MouseButtons.Right) {
283          if (Content.ColumnNames.Count() != 0)
284            contextMenu.Show(MousePosition);
285        }
286      }
287    }
288
289    private void Sort() {
290      int[] newSortedIndex = Enumerable.Range(0, Content.Rows).ToArray();
291      if (sortedColumnIndizes.Count != 0) {
292        rowComparer.sortedIndizes = sortedColumnIndizes;
293        rowComparer.matrix = Content;
294        Array.Sort(newSortedIndex, rowComparer);
295      }
296      virtualRowIndizes = newSortedIndex;
297      UpdateSortGlyph();
298      dataGridView.Invalidate();
299    }
300
301    private void UpdateSortGlyph() {
302      foreach (DataGridViewColumn col in this.dataGridView.Columns)
303        col.HeaderCell.SortGlyphDirection = SortOrder.None;
304      foreach (KeyValuePair<int, SortOrder> p in sortedColumnIndizes)
305        this.dataGridView.Columns[p.Key].HeaderCell.SortGlyphDirection = p.Value;
306    }
307    #endregion
308
309    private class RowComparer : IComparer<int> {
310      public List<KeyValuePair<int, SortOrder>> sortedIndizes;
311      public IStringConvertibleMatrix matrix;
312      public RowComparer() {
313      }
314
315      public int Compare(int x, int y) {
316        int result = 0;
317        double double1, double2;
318        DateTime dateTime1, dateTime2;
319        string string1, string2;
320
321        foreach (KeyValuePair<int, SortOrder> pair in sortedIndizes) {
322          string1 = matrix.GetValue(x, pair.Key);
323          string2 = matrix.GetValue(y, pair.Key);
324          if (double.TryParse(string1, out double1) && double.TryParse(string2, out double2))
325            result = double1.CompareTo(double2);
326          else if (DateTime.TryParse(string1, out dateTime1) && DateTime.TryParse(string2, out dateTime2))
327            result = dateTime1.CompareTo(dateTime2);
328          else {
329            if (string1 != null)
330              result = string1.CompareTo(string2);
331            else if (string2 != null)
332              result = string2.CompareTo(string1) * -1;
333          }
334          if (pair.Value == SortOrder.Descending)
335            result *= -1;
336          if (result != 0)
337            return result;
338        }
339        return result;
340      }
341    }
342
343    private void ShowHideColumns_Click(object sender, EventArgs e) {
344      new ColumnsVisibilityDialog(this.dataGridView.Columns.Cast<DataGridViewColumn>()).ShowDialog();
345    }
346  }
347}
Note: See TracBrowser for help on using the repository browser.