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, 14 years ago

fixed bugs in IStringConvertibleMatrixView (ticket #968)

File size: 14.0 KB
RevLine 
[2669]1#region License Information
2/* HeuristicLab
[2790]3 * Copyright (C) 2002-2010 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;
23using System.ComponentModel;
[3314]24using System.Collections.Generic;
[2669]25using System.Drawing;
[3312]26using System.Linq;
[2669]27using System.Windows.Forms;
28using HeuristicLab.Common;
29using HeuristicLab.MainForm;
[2713]30using HeuristicLab.MainForm.WindowsForms;
[2669]31
32namespace HeuristicLab.Data.Views {
[3048]33  [View("StringConvertibleMatrix View")]
34  [Content(typeof(IStringConvertibleMatrix), true)]
[3228]35  public partial class StringConvertibleMatrixView : AsynchronousContentView {
[3048]36    public new IStringConvertibleMatrix Content {
37      get { return (IStringConvertibleMatrix)base.Content; }
[2713]38      set { base.Content = value; }
[2669]39    }
40
[3314]41    private int[] virtualRowIndizes;
42    private List<KeyValuePair<int, SortOrder>> sortedColumnIndizes;
43    RowComparer rowComparer;
44
[3048]45    public StringConvertibleMatrixView() {
[2669]46      InitializeComponent();
[3048]47      Caption = "StringConvertibleMatrix View";
[2677]48      errorProvider.SetIconAlignment(rowsTextBox, ErrorIconAlignment.MiddleLeft);
49      errorProvider.SetIconPadding(rowsTextBox, 2);
50      errorProvider.SetIconAlignment(columnsTextBox, ErrorIconAlignment.MiddleLeft);
51      errorProvider.SetIconPadding(columnsTextBox, 2);
[3314]52      sortedColumnIndizes = new List<KeyValuePair<int, SortOrder>>();
53      rowComparer = new RowComparer();
[2669]54    }
[3048]55    public StringConvertibleMatrixView(IStringConvertibleMatrix content)
[2669]56      : this() {
[2727]57      Content = content;
[2669]58    }
59
[2713]60    protected override void DeregisterContentEvents() {
61      Content.ItemChanged -= new EventHandler<EventArgs<int, int>>(Content_ItemChanged);
62      Content.Reset -= new EventHandler(Content_Reset);
[3320]63      Content.ColumnNamesChanged -= new EventHandler(Content_ColumnNamesChanged);
64      Content.RowNamesChanged -= new EventHandler(Content_RowNamesChanged);
[3328]65      Content.ReadOnlyViewChanged -= new EventHandler(Content_ReadOnlyViewChanged);
[2713]66      base.DeregisterContentEvents();
[2669]67    }
68
[2713]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);
[3320]73      Content.ColumnNamesChanged += new EventHandler(Content_ColumnNamesChanged);
74      Content.RowNamesChanged += new EventHandler(Content_RowNamesChanged);
[3328]75      Content.ReadOnlyViewChanged += new EventHandler(Content_ReadOnlyViewChanged);
[2669]76    }
77
[3320]78
[2713]79    protected override void OnContentChanged() {
80      base.OnContentChanged();
81      if (Content == null) {
[3048]82        Caption = "StringConvertibleMatrix View";
[2677]83        rowsTextBox.Text = "";
84        rowsTextBox.Enabled = false;
85        columnsTextBox.Text = "";
86        columnsTextBox.Enabled = false;
[2669]87        dataGridView.Rows.Clear();
[2677]88        dataGridView.Columns.Clear();
[2669]89        dataGridView.Enabled = false;
[3324]90        virtualRowIndizes = new int[0];
[2669]91      } else {
[3048]92        Caption = "StringConvertibleMatrix (" + Content.GetType().Name + ")";
[3328]93        UpdateReadOnlyControls();
[2713]94        UpdateData();
[2669]95      }
96    }
97
[2713]98    private void UpdateData() {
[3328]99      sortedColumnIndizes.Clear();
100      Sort();
[2713]101      rowsTextBox.Text = Content.Rows.ToString();
[2973]102      rowsTextBox.Enabled = true;
[2713]103      columnsTextBox.Text = Content.Columns.ToString();
[2973]104      columnsTextBox.Enabled = true;
[3324]105      virtualRowIndizes = Enumerable.Range(0, Content.Rows).ToArray();
[3335]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;
[3328]115      UpdateRowHeaders();
116      UpdateColumnHeaders();
[2669]117      dataGridView.Enabled = true;
118    }
119
[3312]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);
[3314]134        else
[3312]135          dataGridView.Rows[i].HeaderCell.Value = i.ToString();
136      }
137      dataGridView.Invalidate();
138    }
139
[3328]140    private void UpdateReadOnlyControls() {
141      dataGridView.ReadOnly = Content.ReadOnlyView;
142      rowsTextBox.ReadOnly = Content.ReadOnlyView;
143      columnsTextBox.ReadOnly = Content.ReadOnlyView;
144    }
145
[3320]146    private void Content_RowNamesChanged(object sender, EventArgs e) {
[3328]147      if (InvokeRequired)
148        Invoke(new EventHandler(Content_RowNamesChanged), sender, e);
149      else
150        UpdateRowHeaders();
[3320]151    }
152    private void Content_ColumnNamesChanged(object sender, EventArgs e) {
[3328]153      if (InvokeRequired)
154        Invoke(new EventHandler(Content_ColumnNamesChanged), sender, e);
155      else
156        UpdateColumnHeaders();
[3320]157    }
[2713]158    private void Content_ItemChanged(object sender, EventArgs<int, int> e) {
[2669]159      if (InvokeRequired)
[2713]160        Invoke(new EventHandler<EventArgs<int, int>>(Content_ItemChanged), sender, e);
[3328]161      else
[3335]162        dataGridView.InvalidateCell(e.Value2, e.Value);
[2669]163    }
[2713]164    private void Content_Reset(object sender, EventArgs e) {
[2669]165      if (InvokeRequired)
[2713]166        Invoke(new EventHandler(Content_Reset), sender, e);
[2669]167      else
[2713]168        UpdateData();
[2669]169    }
170
[3328]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
[2677]178    #region TextBox Events
179    private void rowsTextBox_Validating(object sender, CancelEventArgs e) {
[2669]180      int i = 0;
[3335]181      if (!int.TryParse(rowsTextBox.Text, out i) || (i <= 0)) {
[2676]182        e.Cancel = true;
[3335]183        errorProvider.SetError(rowsTextBox, "Invalid Number of Rows (Valid values are positive integers larger than 0)");
[2677]184        rowsTextBox.SelectAll();
[2669]185      }
186    }
[2677]187    private void rowsTextBox_Validated(object sender, EventArgs e) {
[3328]188      int textBoxValue = int.Parse(rowsTextBox.Text);
189      if (textBoxValue != Content.Rows)
190        Content.Rows = textBoxValue;
[2677]191      errorProvider.SetError(rowsTextBox, string.Empty);
[2669]192    }
[2677]193    private void rowsTextBox_KeyDown(object sender, KeyEventArgs e) {
[2669]194      if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
[2677]195        rowsLabel.Focus();  // set focus on label to validate data
[2676]196      if (e.KeyCode == Keys.Escape) {
[2973]197        rowsTextBox.Text = Content.Rows.ToString();
[2677]198        rowsLabel.Focus();  // set focus on label to validate data
[2676]199      }
[2669]200    }
[2677]201    private void columnsTextBox_Validating(object sender, CancelEventArgs e) {
202      int i = 0;
[3335]203      if (!int.TryParse(columnsTextBox.Text, out i) || (i <= 0)) {
[2677]204        e.Cancel = true;
[3335]205        errorProvider.SetError(columnsTextBox, "Invalid Number of Columns (Valid values are positive integers larger than 0)");
[2677]206        columnsTextBox.SelectAll();
207      }
208    }
209    private void columnsTextBox_Validated(object sender, EventArgs e) {
[3328]210      int textBoxValue = int.Parse(columnsTextBox.Text);
211      if (textBoxValue != Content.Columns)
212        Content.Columns = textBoxValue;
[2677]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) {
[2713]219        columnsTextBox.Text = Content.Columns.ToString();
[2677]220        columnsLabel.Focus();  // set focus on label to validate data
221      }
222    }
223    #endregion
224
225    #region DataGridView Events
[2669]226    private void dataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) {
[3328]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        }
[2676]233      }
[2669]234    }
[2676]235    private void dataGridView_CellParsing(object sender, DataGridViewCellParsingEventArgs e) {
[3328]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      }
[2669]242    }
[2676]243    private void dataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e) {
244      dataGridView.Rows[e.RowIndex].ErrorText = string.Empty;
245    }
[3312]246    private void dataGridView_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e) {
[3324]247      int rowIndex = virtualRowIndizes[e.RowIndex];
[3335]248      if (e.RowIndex < Content.Rows && e.ColumnIndex < Content.Columns)
249        e.Value = Content.GetValue(rowIndex, e.ColumnIndex);
[3312]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    }
[3314]257
258    private void dataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
[3320]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          }
[3314]268
[3320]269          if (!addToSortedIndizes)
270            sortedColumnIndizes.Clear();
[3314]271
[3320]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        }
[3314]286      }
287    }
288
289    private void Sort() {
[3328]290      int[] newSortedIndex = Enumerable.Range(0, Content.Rows).ToArray();
[3314]291      if (sortedColumnIndizes.Count != 0) {
292        rowComparer.sortedIndizes = sortedColumnIndizes;
293        rowComparer.matrix = Content;
294        Array.Sort(newSortedIndex, rowComparer);
295      }
296      virtualRowIndizes = newSortedIndex;
[3328]297      UpdateSortGlyph();
[3314]298      dataGridView.Invalidate();
[3328]299    }
300
301    private void UpdateSortGlyph() {
[3314]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    }
[2677]307    #endregion
[3312]308
[3314]309    private class RowComparer : IComparer<int> {
310      public List<KeyValuePair<int, SortOrder>> sortedIndizes;
311      public IStringConvertibleMatrix matrix;
312      public RowComparer() {
313      }
[3312]314
[3314]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    }
[3316]342
343    private void ShowHideColumns_Click(object sender, EventArgs e) {
344      new ColumnsVisibilityDialog(this.dataGridView.Columns.Cast<DataGridViewColumn>()).ShowDialog();
345    }
[2669]346  }
347}
Note: See TracBrowser for help on using the repository browser.