Free cookie consent management tool by TermsFeed Policy Generator

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

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

added possibility to change visibility of columns in StringConvertibleMatrixView (ticket #968)

File size: 12.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      base.DeregisterContentEvents();
64    }
65
66
67    protected override void RegisterContentEvents() {
68      base.RegisterContentEvents();
69      Content.ItemChanged += new EventHandler<EventArgs<int, int>>(Content_ItemChanged);
70      Content.Reset += new EventHandler(Content_Reset);
71    }
72
73    protected override void OnContentChanged() {
74      base.OnContentChanged();
75      sortedColumnIndizes.Clear();
76      virtualRowIndizes = new int[0];
77      if (Content == null) {
78        Caption = "StringConvertibleMatrix View";
79        rowsTextBox.Text = "";
80        rowsTextBox.Enabled = false;
81        columnsTextBox.Text = "";
82        columnsTextBox.Enabled = false;
83        dataGridView.Rows.Clear();
84        dataGridView.Columns.Clear();
85        dataGridView.Enabled = false;
86      } else {
87        Caption = "StringConvertibleMatrix (" + Content.GetType().Name + ")";
88        UpdateData();
89      }
90    }
91
92    private void UpdateData() {
93      rowsTextBox.Text = Content.Rows.ToString();
94      rowsTextBox.Enabled = true;
95      columnsTextBox.Text = Content.Columns.ToString();
96      columnsTextBox.Enabled = true;
97      dataGridView.RowCount = 0;
98      dataGridView.ColumnCount = 0;
99      if ((Content.Rows > 0) && (Content.Columns > 0)) {
100        virtualRowIndizes = Enumerable.Range(0, Content.Rows - 1).ToArray();
101        dataGridView.RowCount = Content.Rows;
102        dataGridView.ColumnCount = Content.Columns;
103        UpdateRowHeaders();
104        UpdateColumnHeaders();
105      }
106      dataGridView.Enabled = true;
107    }
108
109    private void UpdateColumnHeaders() {
110      for (int i = 0; i < Content.Columns; i++) {
111        if (Content.ColumnNames.Count() != 0)
112          dataGridView.Columns[i].HeaderText = Content.ColumnNames.ElementAt(i);
113        else
114          dataGridView.Columns[i].HeaderText = "Column " + i;
115      }
116      dataGridView.Invalidate();
117    }
118
119    private void UpdateRowHeaders() {
120      for (int i = dataGridView.FirstDisplayedScrollingRowIndex; i < dataGridView.FirstDisplayedScrollingRowIndex + dataGridView.DisplayedRowCount(true); i++) {
121        if (Content.RowNames.Count() != 0)
122          dataGridView.Rows[i].HeaderCell.Value = Content.RowNames.ElementAt(i);
123        else
124          dataGridView.Rows[i].HeaderCell.Value = i.ToString();
125      }
126      dataGridView.Invalidate();
127    }
128
129    private void Content_ItemChanged(object sender, EventArgs<int, int> e) {
130      if (InvokeRequired)
131        Invoke(new EventHandler<EventArgs<int, int>>(Content_ItemChanged), sender, e);
132      else {
133        dataGridView.InvalidateCell(e.Value, e.Value2);
134      }
135    }
136    private void Content_Reset(object sender, EventArgs e) {
137      if (InvokeRequired)
138        Invoke(new EventHandler(Content_Reset), sender, e);
139      else
140        UpdateData();
141    }
142
143    #region TextBox Events
144    private void rowsTextBox_Validating(object sender, CancelEventArgs e) {
145      int i = 0;
146      if (!int.TryParse(rowsTextBox.Text, out i) || (i < 0)) {
147        e.Cancel = true;
148        errorProvider.SetError(rowsTextBox, "Invalid Number of Rows (Valid Values: Positive Integers Larger or Equal to 0)");
149        rowsTextBox.SelectAll();
150      }
151    }
152    private void rowsTextBox_Validated(object sender, EventArgs e) {
153      Content.Rows = int.Parse(rowsTextBox.Text);
154      errorProvider.SetError(rowsTextBox, string.Empty);
155    }
156    private void rowsTextBox_KeyDown(object sender, KeyEventArgs e) {
157      if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
158        rowsLabel.Focus();  // set focus on label to validate data
159      if (e.KeyCode == Keys.Escape) {
160        rowsTextBox.Text = Content.Rows.ToString();
161        rowsLabel.Focus();  // set focus on label to validate data
162      }
163    }
164    private void columnsTextBox_Validating(object sender, CancelEventArgs e) {
165      int i = 0;
166      if (!int.TryParse(columnsTextBox.Text, out i) || (i < 0)) {
167        e.Cancel = true;
168        errorProvider.SetError(columnsTextBox, "Invalid Number of Columns (Valid Values: Positive Integers Larger or Equal to 0)");
169        columnsTextBox.SelectAll();
170      }
171    }
172    private void columnsTextBox_Validated(object sender, EventArgs e) {
173      Content.Columns = int.Parse(columnsTextBox.Text);
174      errorProvider.SetError(columnsTextBox, string.Empty);
175    }
176    private void columnsTextBox_KeyDown(object sender, KeyEventArgs e) {
177      if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
178        columnsLabel.Focus();  // set focus on label to validate data
179      if (e.KeyCode == Keys.Escape) {
180        columnsTextBox.Text = Content.Columns.ToString();
181        columnsLabel.Focus();  // set focus on label to validate data
182      }
183    }
184    #endregion
185
186    #region DataGridView Events
187    private void dataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) {
188      string errorMessage;
189      if (!Content.Validate(e.FormattedValue.ToString(), out errorMessage)) {
190        e.Cancel = true;
191        dataGridView.Rows[e.RowIndex].ErrorText = errorMessage;
192      }
193    }
194    private void dataGridView_CellParsing(object sender, DataGridViewCellParsingEventArgs e) {
195      string value = e.Value.ToString();
196      int rowIndex = virtualRowIndizes[e.RowIndex];
197      e.ParsingApplied = Content.SetValue(value, rowIndex, e.ColumnIndex);
198      if (e.ParsingApplied) e.Value = Content.GetValue(rowIndex, e.ColumnIndex);
199    }
200    private void dataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e) {
201      dataGridView.Rows[e.RowIndex].ErrorText = string.Empty;
202    }
203    private void dataGridView_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e) {
204      if (e.RowIndex < virtualRowIndizes.Length) {
205        int rowIndex = virtualRowIndizes[e.RowIndex];
206        e.Value = Content.GetValue(rowIndex, e.ColumnIndex);
207      }
208    }
209
210    private void dataGridView_Scroll(object sender, ScrollEventArgs e) {
211      UpdateRowHeaders();
212    }
213
214    private void dataGridView_Resize(object sender, EventArgs e) {
215      UpdateRowHeaders();
216    }
217
218    private void dataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
219      //if (Content != null && Content.SortableView) {
220      if (e.Button == MouseButtons.Left) {
221        bool addToSortedIndizes = (Control.ModifierKeys & Keys.Control) == Keys.Control;
222        SortOrder newSortOrder = SortOrder.Ascending;
223        if (sortedColumnIndizes.Any(x => x.Key == e.ColumnIndex)) {
224          SortOrder oldSortOrder = sortedColumnIndizes.Where(x => x.Key == e.ColumnIndex).First().Value;
225          int enumLength = Enum.GetValues(typeof(SortOrder)).Length;
226          newSortOrder = oldSortOrder = (SortOrder)Enum.Parse(typeof(SortOrder), ((((int)oldSortOrder) + 1) % enumLength).ToString());
227        }
228
229        if (!addToSortedIndizes)
230          sortedColumnIndizes.Clear();
231
232        if (sortedColumnIndizes.Any(x => x.Key == e.ColumnIndex)) {
233          int sortedIndex = sortedColumnIndizes.FindIndex(x => x.Key == e.ColumnIndex);
234          if (newSortOrder != SortOrder.None)
235            sortedColumnIndizes[sortedIndex] = new KeyValuePair<int, SortOrder>(e.ColumnIndex, newSortOrder);
236          else
237            sortedColumnIndizes.RemoveAt(sortedIndex);
238        } else
239          if (newSortOrder != SortOrder.None)
240            sortedColumnIndizes.Add(new KeyValuePair<int, SortOrder>(e.ColumnIndex, newSortOrder));
241        Sort();
242      } else if (e.Button == MouseButtons.Right) {
243        if (Content.ColumnNames.Count() != 0)
244          contextMenu.Show(MousePosition);
245      }
246
247      //}
248    }
249
250    private void Sort() {
251      int[] newSortedIndex = Enumerable.Range(0, Content.Rows - 1).ToArray();
252      if (sortedColumnIndizes.Count != 0) {
253        rowComparer.sortedIndizes = sortedColumnIndizes;
254        rowComparer.matrix = Content;
255        Array.Sort(newSortedIndex, rowComparer);
256      }
257      virtualRowIndizes = newSortedIndex;
258      dataGridView.Invalidate();
259      foreach (DataGridViewColumn col in this.dataGridView.Columns)
260        col.HeaderCell.SortGlyphDirection = SortOrder.None;
261      foreach (KeyValuePair<int, SortOrder> p in sortedColumnIndizes)
262        this.dataGridView.Columns[p.Key].HeaderCell.SortGlyphDirection = p.Value;
263    }
264    #endregion
265
266    private class RowComparer : IComparer<int> {
267      public List<KeyValuePair<int, SortOrder>> sortedIndizes;
268      public IStringConvertibleMatrix matrix;
269      public RowComparer() {
270      }
271
272      public int Compare(int x, int y) {
273        int result = 0;
274        double double1, double2;
275        DateTime dateTime1, dateTime2;
276        string string1, string2;
277
278        foreach (KeyValuePair<int, SortOrder> pair in sortedIndizes) {
279          string1 = matrix.GetValue(x, pair.Key);
280          string2 = matrix.GetValue(y, pair.Key);
281          if (double.TryParse(string1, out double1) && double.TryParse(string2, out double2))
282            result = double1.CompareTo(double2);
283          else if (DateTime.TryParse(string1, out dateTime1) && DateTime.TryParse(string2, out dateTime2))
284            result = dateTime1.CompareTo(dateTime2);
285          else {
286            if (string1 != null)
287              result = string1.CompareTo(string2);
288            else if (string2 != null)
289              result = string2.CompareTo(string1) * -1;
290          }
291          if (pair.Value == SortOrder.Descending)
292            result *= -1;
293          if (result != 0)
294            return result;
295        }
296        return result;
297      }
298    }
299
300    private void ShowHideColumns_Click(object sender, EventArgs e) {
301      new ColumnsVisibilityDialog(this.dataGridView.Columns.Cast<DataGridViewColumn>()).ShowDialog();
302    }
303  }
304}
Note: See TracBrowser for help on using the repository browser.