source: branches/DataPreprocessing Enhancements/HeuristicLab.DataPreprocessing.Views/3.4/DataGridContentView.cs @ 14525

Last change on this file since 14525 was 14525, checked in by pfleck, 5 years ago

#2709

  • Added suggestion feature for singlescatterplotview.
  • Shows NaN groups in scatterplot (black if gradient is selected).
  • Only enables input variables in DataGridContentView per default.
  • Added missing resx file (gradient image).
File size: 26.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 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.Collections.Generic;
24using System.Linq;
25using System.Windows.Forms;
26using HeuristicLab.Data;
27using HeuristicLab.Data.Views;
28using HeuristicLab.DataPreprocessing.Filter;
29using HeuristicLab.MainForm;
30
31namespace HeuristicLab.DataPreprocessing.Views {
32  [View("Data Grid Content View")]
33  [Content(typeof(DataGridContent), true)]
34  public partial class DataGridContentView : StringConvertibleMatrixView {
35
36    private bool isSearching = false;
37    private bool updateOnMouseUp = false;
38    private SearchAndReplaceDialog findAndReplaceDialog;
39    private IFindPreprocessingItemsIterator searchIterator;
40    private string currentSearchText;
41    private ComparisonOperation currentComparisonOperation;
42    private Tuple<int, int> currentCell;
43
44    public new DataGridContent Content {
45      get { return (DataGridContent)base.Content; }
46      set { base.Content = value; }
47    }
48
49    private IDictionary<int, IList<int>> _highlightedCellsBackground;
50    public IDictionary<int, IList<int>> HightlightedCellsBackground {
51      get { return _highlightedCellsBackground; }
52      set {
53        _highlightedCellsBackground = value;
54        Refresh();
55      }
56    }
57
58    public DataGridContentView() {
59      InitializeComponent();
60      dataGridView.CellMouseClick += dataGridView_CellMouseClick;
61      dataGridView.RowHeaderMouseClick += dataGridView_RowHeaderMouseClick;
62      dataGridView.KeyDown += dataGridView_KeyDown;
63      dataGridView.MouseUp += dataGridView_MouseUp;
64      contextMenuCell.Items.Add(ShowHideColumns);
65      _highlightedCellsBackground = new Dictionary<int, IList<int>>();
66      currentCell = null;
67    }
68
69    protected override void OnContentChanged() {
70      List<KeyValuePair<int, SortOrder>> order = new List<KeyValuePair<int, SortOrder>>(base.sortedColumnIndices);
71      base.OnContentChanged();
72
73      foreach (DataGridViewColumn column in DataGridView.Columns) {
74        var variable = column.HeaderText;
75        bool isInputTarget = Content.PreProcessingData.InputVariables.Contains(variable)
76          || Content.PreProcessingData.TargetVariable == variable;
77        column.Visible = isInputTarget;
78      }
79
80      DataGridView.RowHeadersWidth = 70;
81
82      if (Content == null && findAndReplaceDialog != null) {
83        findAndReplaceDialog.Close();
84      }
85
86      if (Content != null) {
87        base.sortedColumnIndices = order;
88        base.Sort();
89      }
90
91    }
92
93    protected override void RegisterContentEvents() {
94      base.RegisterContentEvents();
95      Content.Changed += Content_Changed;
96      Content.FilterLogic.FilterChanged += FilterLogic_FilterChanged;
97    }
98
99    protected override void DeregisterContentEvents() {
100      base.DeregisterContentEvents();
101      Content.Changed -= Content_Changed;
102      Content.FilterLogic.FilterChanged -= FilterLogic_FilterChanged;
103    }
104
105    private void FilterLogic_FilterChanged(object sender, EventArgs e) {
106      OnContentChanged();
107      searchIterator = null;
108      if (findAndReplaceDialog != null && !findAndReplaceDialog.IsDisposed) {
109        if (Content.FilterLogic.IsFiltered) {
110          findAndReplaceDialog.DisableReplace();
111        } else {
112          findAndReplaceDialog.EnableReplace();
113        }
114      }
115      btnReplace.Enabled = !Content.FilterLogic.IsFiltered;
116    }
117
118    private void Content_Changed(object sender, DataPreprocessingChangedEventArgs e) {
119      OnContentChanged();
120      searchIterator = null;
121    }
122
123    protected override void dataGridView_SelectionChanged(object sender, EventArgs e) {
124      base.dataGridView_SelectionChanged(sender, e);
125      if (Content != null && dataGridView.RowCount != 0 && dataGridView.ColumnCount != 0)
126        Content.Selection = GetSelectedCells();
127    }
128
129    //couldn't use base.dataGridView_CellValidating as the values have to be validated per column individually
130    protected override void dataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) {
131      if (dataGridView.ReadOnly) return;
132      if (Content == null) return;
133      if (Content.Rows == 0 || Content.Columns == 0) return;
134
135      string errorMessage;
136      if (!String.IsNullOrEmpty(e.FormattedValue.ToString())) {
137        if (dataGridView.IsCurrentCellInEditMode && Content.FilterLogic.IsFiltered) {
138          errorMessage = "A filter is active, you cannot modify data. Press ESC to exit edit mode.";
139        } else {
140          Content.Validate(e.FormattedValue.ToString(), out errorMessage, e.ColumnIndex);
141        }
142
143        if (!String.IsNullOrEmpty(errorMessage)) {
144          e.Cancel = true;
145          dataGridView.Rows[e.RowIndex].ErrorText = errorMessage;
146        }
147
148      }
149    }
150
151
152    protected override void PasteValuesToDataGridView() {
153      string[,] values = SplitClipboardString(Clipboard.GetText());
154      if (values.Length == 0) return;
155      int rowIndex = 0;
156      int columnIndex = 0;
157      if (dataGridView.CurrentCell != null) {
158        rowIndex = dataGridView.CurrentCell.RowIndex;
159        columnIndex = dataGridView.CurrentCell.ColumnIndex;
160      }
161
162      bool containsHeader = false;
163      var firstRow = Enumerable.Range(0, values.GetLength(0)).Select(col => values[col, 0]).ToList();
164      if ((Content.Selection.Values.Sum(s => s.Count) == Content.Rows * Content.Columns)
165          || (rowIndex == 0 && columnIndex == 0 && Content.Rows <= values.GetLength(1) && Content.Columns <= values.GetLength(0))) {
166        // All is selected -or- top left selected and everything will be replaced
167        double temp;
168        containsHeader = !firstRow.All(string.IsNullOrEmpty) && firstRow.Any(r => !double.TryParse(r, out temp));
169        if (containsHeader)
170          rowIndex = columnIndex = 0;
171      }
172
173      int newRows = values.GetLength(1) + rowIndex - (containsHeader ? 1 : 0);
174      int newColumns = values.GetLength(0) + columnIndex;
175      if (Content.Rows < newRows) Content.Rows = newRows;
176      if (Content.Columns < newColumns) Content.Columns = newColumns;
177
178      ReplaceTransaction(() => {
179        Content.PreProcessingData.InTransaction(() => {
180          for (int row = containsHeader ? 1 : 0; row < values.GetLength(1); row++) {
181            for (int col = 0; col < values.GetLength(0); col++) {
182              Content.SetValue(values[col, row], row + rowIndex - (containsHeader ? 1 : 0), col + columnIndex);
183            }
184          }
185          if (containsHeader) {
186            for (int i = 0; i < firstRow.Count; i++)
187              if (string.IsNullOrWhiteSpace(firstRow[i]))
188                firstRow[i] = string.Format("<{0}>", i);
189            Content.PreProcessingData.RenameColumns(firstRow);
190          }
191        });
192      });
193
194      ClearSorting();
195    }
196
197    protected override void SetEnabledStateOfControls() {
198      base.SetEnabledStateOfControls();
199      rowsTextBox.ReadOnly = true;
200      columnsTextBox.ReadOnly = true;
201    }
202
203    protected override int[] Sort(IEnumerable<KeyValuePair<int, SortOrder>> sortedColumns) {
204      btnApplySort.Enabled = sortedColumns.Any();
205      return base.Sort(sortedColumns);
206    }
207
208    protected override void ClearSorting() {
209      btnApplySort.Enabled = false;
210      base.ClearSorting();
211    }
212
213    protected override void dataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
214      if (Content != null) {
215        if (e.Button == MouseButtons.Left) {
216          dataGridView.Focus();
217          dataGridView.ClearSelection();
218          dataGridView.SelectionChanged -= dataGridView_SelectionChanged;
219          for (int i = 0; i < dataGridView.RowCount; i++) {
220            if (i + 1 == dataGridView.RowCount)
221              dataGridView.SelectionChanged += dataGridView_SelectionChanged;
222            dataGridView[e.ColumnIndex, i].Selected = true;
223          }
224        } else if (e.Button == MouseButtons.Middle) {
225          int newIndex = e.ColumnIndex >= 0 ? e.ColumnIndex : 0;
226          Content.PreProcessingData.InsertColumn<double>(newIndex.ToString(), newIndex);
227        } else if (e.Button == MouseButtons.Right && Content.SortableView) {
228          SortColumn(e.ColumnIndex);
229        }
230      }
231      searchIterator = null;
232    }
233    private void dataGridView_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
234      if (Content != null) {
235        if (e.Button == MouseButtons.Middle) {
236          int newIndex = e.RowIndex >= 0 ? e.RowIndex : 0;
237          Content.PreProcessingData.InsertRow(newIndex);
238        }
239      }
240    }
241
242    private void dataGridView_MouseUp(object sender, MouseEventArgs e) {
243      if (!updateOnMouseUp)
244        return;
245
246      updateOnMouseUp = false;
247      dataGridView_SelectionChanged(sender, e);
248    }
249
250    private void btnApplySort_Click(object sender, System.EventArgs e) {
251      Content.ManipulationLogic.ReOrderToIndices(virtualRowIndices);
252      OnContentChanged();
253    }
254
255    #region FindAndReplaceDialog
256
257    private void CreateFindAndReplaceDialog() {
258      if (findAndReplaceDialog == null || findAndReplaceDialog.IsDisposed) {
259        findAndReplaceDialog = new SearchAndReplaceDialog();
260        findAndReplaceDialog.Show(this);
261        if (AreMultipleCellsSelected()) {
262          ResetHighlightedCellsBackground();
263          HightlightedCellsBackground = GetSelectedCells();
264          dataGridView.ClearSelection();
265        }
266        findAndReplaceDialog.FindAllEvent += findAndReplaceDialog_FindAllEvent;
267        findAndReplaceDialog.FindNextEvent += findAndReplaceDialog_FindNextEvent;
268        findAndReplaceDialog.ReplaceAllEvent += findAndReplaceDialog_ReplaceAllEvent;
269        findAndReplaceDialog.ReplaceNextEvent += findAndReplaceDialog_ReplaceEvent;
270        findAndReplaceDialog.FormClosing += findAndReplaceDialog_FormClosing;
271        searchIterator = null;
272        DataGridView.SelectionChanged += DataGridView_SelectionChanged_FindAndReplace;
273        if (Content.FilterLogic.IsFiltered) {
274          findAndReplaceDialog.DisableReplace();
275        }
276      }
277    }
278
279    private void DataGridView_SelectionChanged_FindAndReplace(object sender, EventArgs e) {
280      if (Content != null) {
281        if (!isSearching && AreMultipleCellsSelected()) {
282          ResetHighlightedCellsBackground();
283          HightlightedCellsBackground = GetSelectedCells();
284          searchIterator = null;
285        }
286      }
287    }
288
289    void findAndReplaceDialog_FormClosing(object sender, FormClosingEventArgs e) {
290      ResetHighlightedCellsBackground();
291      searchIterator = null;
292      DataGridView.SelectionChanged -= DataGridView_SelectionChanged_FindAndReplace;
293    }
294
295    void findAndReplaceDialog_ReplaceEvent(object sender, EventArgs e) {
296      if (searchIterator != null && searchIterator.GetCurrent() != null) {
297        Replace(TransformToDictionary(currentCell));
298      }
299    }
300
301    void findAndReplaceDialog_ReplaceAllEvent(object sender, EventArgs e) {
302      Replace(FindAll(findAndReplaceDialog.GetSearchText()));
303    }
304
305    void findAndReplaceDialog_FindNextEvent(object sender, EventArgs e) {
306      if (searchIterator == null
307        || currentSearchText != findAndReplaceDialog.GetSearchText()
308        || currentComparisonOperation != findAndReplaceDialog.GetComparisonOperation()) {
309
310        searchIterator = new FindPreprocessingItemsIterator(FindAll(findAndReplaceDialog.GetSearchText()));
311        currentSearchText = findAndReplaceDialog.GetSearchText();
312        currentComparisonOperation = findAndReplaceDialog.GetComparisonOperation();
313      }
314
315      if (IsOneCellSelected()) {
316        var first = GetSelectedCells().First();
317        searchIterator.SetStartCell(first.Key, first.Value[0]);
318      }
319
320      bool moreOccurences = false;
321      currentCell = searchIterator.GetCurrent();
322      moreOccurences = searchIterator.MoveNext();
323      if (IsOneCellSelected() && currentCell != null) {
324        var first = GetSelectedCells().First();
325        if (currentCell.Item1 == first.Key && currentCell.Item2 == first.Value[0]) {
326          if (!moreOccurences) {
327            searchIterator.Reset();
328          }
329          currentCell = searchIterator.GetCurrent();
330          moreOccurences = searchIterator.MoveNext();
331          if (!moreOccurences) {
332            searchIterator.Reset();
333          }
334        }
335      }
336
337      dataGridView.ClearSelection();
338
339      if (currentCell != null) {
340        dataGridView[currentCell.Item1, currentCell.Item2].Selected = true;
341        dataGridView.CurrentCell = dataGridView[currentCell.Item1, currentCell.Item2];
342      }
343    }
344
345    private bool AreMultipleCellsSelected() {
346      return GetSelectedCellCount() > 1;
347    }
348
349    private bool IsOneCellSelected() {
350      return GetSelectedCellCount() == 1;
351    }
352
353    private int GetSelectedCellCount() {
354      int count = 0;
355      foreach (var column in GetSelectedCells()) {
356        count += column.Value.Count();
357      }
358      return count;
359    }
360
361    void findAndReplaceDialog_FindAllEvent(object sender, EventArgs e) {
362      dataGridView.ClearSelection();
363      isSearching = true;
364      SuspendRepaint();
365      var selectedCells = FindAll(findAndReplaceDialog.GetSearchText());
366      foreach (var column in selectedCells) {
367        foreach (var cell in column.Value) {
368          dataGridView[column.Key, cell].Selected = true;
369        }
370      }
371      ResumeRepaint(true);
372      isSearching = false;
373      Content.Selection = selectedCells;
374      //update statistic in base
375      base.dataGridView_SelectionChanged(sender, e);
376    }
377
378    private Core.ConstraintOperation GetConstraintOperation(ComparisonOperation comparisonOperation) {
379      Core.ConstraintOperation constraintOperation = Core.ConstraintOperation.Equal;
380      switch (comparisonOperation) {
381        case ComparisonOperation.Equal:
382          constraintOperation = Core.ConstraintOperation.Equal;
383          break;
384        case ComparisonOperation.Greater:
385          constraintOperation = Core.ConstraintOperation.Greater;
386          break;
387        case ComparisonOperation.GreaterOrEqual:
388          constraintOperation = Core.ConstraintOperation.GreaterOrEqual;
389          break;
390        case ComparisonOperation.Less:
391          constraintOperation = Core.ConstraintOperation.Less;
392          break;
393        case ComparisonOperation.LessOrEqual:
394          constraintOperation = Core.ConstraintOperation.LessOrEqual;
395          break;
396        case ComparisonOperation.NotEqual:
397          constraintOperation = Core.ConstraintOperation.NotEqual;
398          break;
399      }
400      return constraintOperation;
401    }
402
403    private IDictionary<int, IList<int>> FindAll(string match) {
404      bool searchInSelection = HightlightedCellsBackground.Values.Sum(list => list.Count) > 1;
405      ComparisonOperation comparisonOperation = findAndReplaceDialog.GetComparisonOperation();
406      var foundCells = new Dictionary<int, IList<int>>();
407      for (int i = 0; i < Content.FilterLogic.PreprocessingData.Columns; i++) {
408        var filters = CreateFilters(match, comparisonOperation, i);
409
410        bool[] filteredRows = Content.FilterLogic.GetFilterResult(filters, true);
411        var foundIndices = new List<int>();
412        for (int idx = 0; idx < filteredRows.Length; ++idx) {
413          var notFilteredThusFound = !filteredRows[idx];
414          if (notFilteredThusFound) {
415            foundIndices.Add(idx);
416          }
417        }
418        foundCells[i] = foundIndices;
419        IList<int> selectedList;
420        if (searchInSelection && HightlightedCellsBackground.TryGetValue(i, out selectedList)) {
421          foundCells[i] = foundCells[i].Intersect(selectedList).ToList<int>();
422        } else if (searchInSelection) {
423          foundCells[i].Clear();
424        }
425      }
426      return MapToSorting(foundCells);
427    }
428
429    private List<IFilter> CreateFilters(string match, ComparisonOperation comparisonOperation, int columnIndex) {
430      IPreprocessingData preprocessingData = Content.FilterLogic.PreprocessingData;
431      IStringConvertibleValue value;
432      if (preprocessingData.VariableHasType<double>(columnIndex)) {
433        value = new DoubleValue();
434      } else if (preprocessingData.VariableHasType<String>(columnIndex)) {
435        value = new StringValue();
436      } else if (preprocessingData.VariableHasType<DateTime>(columnIndex)) {
437        value = new DateTimeValue();
438      } else {
439        throw new ArgumentException("unsupported type");
440      }
441      value.SetValue(match);
442      var comparisonFilter = new ComparisonFilter(preprocessingData, GetConstraintOperation(comparisonOperation), value, true);
443      comparisonFilter.ConstraintColumn = columnIndex;
444      return new List<Filter.IFilter>() { comparisonFilter };
445    }
446
447    private IDictionary<int, IList<int>> MapToSorting(Dictionary<int, IList<int>> foundCells) {
448      if (sortedColumnIndices.Count == 0) {
449        return foundCells;
450      } else {
451        var sortedFoundCells = new Dictionary<int, IList<int>>();
452
453        var indicesToVirtual = new Dictionary<int, int>();
454        for (int i = 0; i < virtualRowIndices.Length; ++i) {
455          indicesToVirtual.Add(virtualRowIndices[i], i);
456        }
457
458        foreach (var entry in foundCells) {
459          var cells = new List<int>();
460          foreach (var cell in entry.Value) {
461            cells.Add(indicesToVirtual[cell]);
462          }
463          cells.Sort();
464          sortedFoundCells.Add(entry.Key, cells);
465        }
466        return sortedFoundCells;
467      }
468    }
469
470    private void Replace(IDictionary<int, IList<int>> cells) {
471      if (findAndReplaceDialog != null) {
472        ReplaceTransaction(() => {
473          switch (findAndReplaceDialog.GetReplaceAction()) {
474            case ReplaceAction.Value:
475              Content.ManipulationLogic.ReplaceIndicesByValue(cells, findAndReplaceDialog.GetReplaceText());
476              break;
477            case ReplaceAction.Average:
478              Content.ManipulationLogic.ReplaceIndicesByAverageValue(cells, false);
479              break;
480            case ReplaceAction.Median:
481              Content.ManipulationLogic.ReplaceIndicesByMedianValue(cells, false);
482              break;
483            case ReplaceAction.Random:
484              Content.ManipulationLogic.ReplaceIndicesByRandomValue(cells, false);
485              break;
486            case ReplaceAction.MostCommon:
487              Content.ManipulationLogic.ReplaceIndicesByMostCommonValue(cells, false);
488              break;
489            case ReplaceAction.Interpolation:
490              Content.ManipulationLogic.ReplaceIndicesByLinearInterpolationOfNeighbours(cells);
491              break;
492          }
493        });
494      }
495    }
496
497    private IDictionary<int, IList<int>> TransformToDictionary(Tuple<int, int> tuple) {
498      var highlightCells = new Dictionary<int, IList<int>>();
499      highlightCells.Add(tuple.Item1, new List<int>() { tuple.Item2 });
500      return highlightCells;
501    }
502
503    private void ResetHighlightedCellsBackground() {
504      HightlightedCellsBackground = new Dictionary<int, IList<int>>();
505    }
506
507    #endregion FindAndReplaceDialog
508
509    private void dataGridView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
510      if (Content == null) return;
511      if (e.Button == MouseButtons.Right && !(e.ColumnIndex != -1 && e.RowIndex == -1)) {
512        if (e.ColumnIndex == -1 || e.RowIndex == -1) {
513          replaceValueOverColumnToolStripMenuItem.Visible = false;
514          contextMenuCell.Show(MousePosition);
515        } else {
516          if (!dataGridView.SelectedCells.Contains(dataGridView[e.ColumnIndex, e.RowIndex])) {
517            dataGridView.ClearSelection();
518            dataGridView[e.ColumnIndex, e.RowIndex].Selected = true;
519          }
520
521          var columnIndices = new HashSet<int>();
522          for (int i = 0; i < dataGridView.SelectedCells.Count; i++) {
523            columnIndices.Add(dataGridView.SelectedCells[i].ColumnIndex);
524          }
525
526          replaceValueOverSelectionToolStripMenuItem.Enabled = AreMultipleCellsSelected();
527
528          averageToolStripMenuItem_Column.Enabled =
529            averageToolStripMenuItem_Selection.Enabled =
530            medianToolStripMenuItem_Column.Enabled =
531            medianToolStripMenuItem_Selection.Enabled =
532            randomToolStripMenuItem_Column.Enabled =
533            randomToolStripMenuItem_Selection.Enabled = !Content.PreProcessingData.AreAllStringColumns(columnIndices);
534
535          smoothingToolStripMenuItem_Column.Enabled =
536            interpolationToolStripMenuItem_Column.Enabled = !dataGridView.SelectedCells.Contains(dataGridView[e.ColumnIndex, 0])
537            && !dataGridView.SelectedCells.Contains(dataGridView[e.ColumnIndex, Content.Rows - 1])
538            && !Content.PreProcessingData.AreAllStringColumns(columnIndices);
539
540          replaceValueOverColumnToolStripMenuItem.Visible = true;
541          contextMenuCell.Show(MousePosition);
542        }
543      }
544    }
545
546    protected override void dataGridView_KeyDown(object sender, KeyEventArgs e) {
547      var selectedRows = dataGridView.SelectedRows;
548      var selectedCells = dataGridView.SelectedCells;
549      if (!Content.FilterLogic.IsFiltered) { //data is in read only mode....
550        if (e.KeyCode == Keys.Delete && selectedCells.Count == Content.Rows && selectedCells.Count > 0) {
551          Content.DeleteColumn(selectedCells[0].ColumnIndex);
552        } else if (e.KeyCode == Keys.Delete && selectedRows.Count > 0) {
553          List<int> rows = new List<int>();
554          for (int i = 0; i < selectedRows.Count; ++i) {
555            int index = (sortedColumnIndices.Count != 0) ? (Convert.ToInt32(selectedRows[i].HeaderCell.Value) - 1) :
556              selectedRows[i].Index;
557            rows.Add(index);
558          }
559          Content.DeleteRows(rows);
560        } else if (e.Control && e.KeyCode == Keys.F) {
561          CreateFindAndReplaceDialog();
562          findAndReplaceDialog.ActivateSearch();
563        } else if (e.Control && e.KeyCode == Keys.R) {
564          CreateFindAndReplaceDialog();
565          findAndReplaceDialog.ActivateReplace();
566        }
567      }
568    }
569
570    private IDictionary<int, IList<int>> GetSelectedCells() {
571      IDictionary<int, IList<int>> selectedCells = new Dictionary<int, IList<int>>();
572
573      //special case if all cells are selected
574      if (dataGridView.AreAllCellsSelected(true)) {
575        for (int i = 0; i < Content.Columns; i++)
576          selectedCells[i] = Enumerable.Range(0, Content.Rows).ToList();
577        return selectedCells;
578      }
579
580      foreach (var selectedCell in dataGridView.SelectedCells) {
581        var cell = (DataGridViewCell)selectedCell;
582        if (!selectedCells.ContainsKey(cell.ColumnIndex))
583          selectedCells.Add(cell.ColumnIndex, new List<int>(1024));
584        selectedCells[cell.ColumnIndex].Add(cell.RowIndex);
585      }
586
587      return selectedCells;
588    }
589
590    private void StartReplacing() {
591      SuspendRepaint();
592    }
593
594    private void StopReplacing() {
595      ResumeRepaint(true);
596    }
597
598    private void ReplaceTransaction(Action action) {
599      StartReplacing();
600      action();
601      StopReplacing();
602    }
603
604    private void btnSearch_Click(object sender, EventArgs e) {
605      CreateFindAndReplaceDialog();
606      findAndReplaceDialog.ActivateSearch();
607    }
608
609    private void btnReplace_Click(object sender, EventArgs e) {
610      CreateFindAndReplaceDialog();
611      findAndReplaceDialog.ActivateReplace();
612    }
613
614    #region ContextMenu Events
615
616    private void ReplaceWithAverage_Column_Click(object sender, EventArgs e) {
617      ReplaceTransaction(() => {
618        Content.ManipulationLogic.ReplaceIndicesByAverageValue(GetSelectedCells(), false);
619      });
620    }
621    private void ReplaceWithAverage_Selection_Click(object sender, EventArgs e) {
622      ReplaceTransaction(() => {
623        Content.ManipulationLogic.ReplaceIndicesByAverageValue(GetSelectedCells(), true);
624      });
625    }
626
627    private void ReplaceWithMedian_Column_Click(object sender, EventArgs e) {
628      ReplaceTransaction(() => {
629        Content.ManipulationLogic.ReplaceIndicesByMedianValue(GetSelectedCells(), false);
630      });
631    }
632    private void ReplaceWithMedian_Selection_Click(object sender, EventArgs e) {
633      ReplaceTransaction(() => {
634        Content.ManipulationLogic.ReplaceIndicesByMedianValue(GetSelectedCells(), true);
635      });
636    }
637
638    private void ReplaceWithRandom_Column_Click(object sender, EventArgs e) {
639      ReplaceTransaction(() => {
640        Content.ManipulationLogic.ReplaceIndicesByRandomValue(GetSelectedCells(), false);
641      });
642    }
643    private void ReplaceWithRandom_Selection_Click(object sender, EventArgs e) {
644      ReplaceTransaction(() => {
645        Content.ManipulationLogic.ReplaceIndicesByRandomValue(GetSelectedCells(), true);
646      });
647    }
648
649    private void ReplaceWithMostCommon_Column_Click(object sender, EventArgs e) {
650      ReplaceTransaction(() => {
651        Content.ManipulationLogic.ReplaceIndicesByMostCommonValue(GetSelectedCells(), false);
652      });
653    }
654    private void ReplaceWithMostCommon_Selection_Click(object sender, EventArgs e) {
655      ReplaceTransaction(() => {
656        Content.ManipulationLogic.ReplaceIndicesByMostCommonValue(GetSelectedCells(), true);
657      });
658    }
659
660    private void ReplaceWithInterpolation_Column_Click(object sender, EventArgs e) {
661      ReplaceTransaction(() => {
662        Content.ManipulationLogic.ReplaceIndicesByLinearInterpolationOfNeighbours(GetSelectedCells());
663      });
664    }
665
666    private void ReplaceWithSmoothing_Selection_Click(object sender, EventArgs e) {
667      ReplaceTransaction(() => {
668        Content.ManipulationLogic.ReplaceIndicesBySmoothing(GetSelectedCells());
669      });
670    }
671    #endregion
672
673    private void addRowButton_Click(object sender, EventArgs e) {
674      Content.PreProcessingData.InsertRow(Content.Rows);
675    }
676
677    private void addColumnButton_Click(object sender, EventArgs e) {
678      Content.PreProcessingData.InsertColumn<double>(Content.Columns.ToString(), Content.Columns);
679    }
680
681    private void renameColumnsButton_Click(object sender, EventArgs e) {
682      var renameDialog = new RenameColumnsDialog(Content.ColumnNames);
683
684      if (renameDialog.ShowDialog(this) == DialogResult.OK) {
685        Content.PreProcessingData.RenameColumns(renameDialog.ColumnNames);
686      }
687    }
688  }
689}
Note: See TracBrowser for help on using the repository browser.