Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.DataImporter/HeuristicLab.DataImporter.Data/View/ColumnGroupView.cs @ 8614

Last change on this file since 8614 was 7994, checked in by sforsten, 13 years ago

#1867: corrected some mistakes

File size: 26.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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.Drawing;
25using System.Linq;
26using System.Text;
27using System.Windows.Forms;
28using HeuristicLab.DataImporter.Data.Command;
29using HeuristicLab.DataImporter.Data.Model;
30
31
32namespace HeuristicLab.DataImporter.Data.View {
33  public delegate void ColumnGroupActivatedEventHandler(object sender, bool addToActiveColumnGroups);
34  public partial class ColumnGroupView : UserControl {
35
36    private TextBox txtColumnName;
37    private ColumnGroupView()
38      : base() {
39      InitializeComponent();
40      txtColumnName = new TextBox();
41      this.splitContainer1.Panel2.Controls.Add(txtColumnName);
42      txtColumnName.Visible = false;
43      txtColumnName.Leave += new EventHandler(txtColumnName_Leave);
44      txtColumnName.KeyDown += new KeyEventHandler(txtColumnName_KeyDown);
45
46      this.dataGridView.EnableHeadersVisualStyles = false;
47      this.dataGridView.Dock = DockStyle.Top | DockStyle.Bottom;
48      this.dataGridView.VirtualMode = true;
49      this.dataGridView.ShowCellToolTips = false;
50
51      this.dataGridView.ColumnHeaderMouseClick += new DataGridViewCellMouseEventHandler(dataGridView_ColumnHeaderMouseClick);
52      this.dataGridView.ColumnHeaderMouseDoubleClick += new DataGridViewCellMouseEventHandler(dataGridView_ColumnHeaderMouseDoubleClick);
53      this.dataGridView.ColumnWidthChanged += new DataGridViewColumnEventHandler(dataGridView_ColumnWidthChanged);
54      this.dataGridView.MouseClick += new MouseEventHandler(dataGridView_MouseClick);
55      this.dataGridView.SelectionChanged += new EventHandler(dataGridView_SelectionChanged);
56      this.dataGridView.AllowUserToOrderColumnsChanged += new EventHandler(dataGridView_AllowUserToOrderColumnsChanged);
57      this.dataGridView.KeyDown += new KeyEventHandler(dataGridView_KeyDown);
58      this.dataGridView.RowHeadersWidthChanged += new EventHandler(dataGridView_RowHeadersWidthChanged);
59      this.dataGridView.CellMouseEnter += new DataGridViewCellEventHandler(dataGridView_CellMouseEnter);
60      this.dataGridView.Scroll += new ScrollEventHandler(dataGridView_Scroll);
61      this.dataGridView.Resize += new EventHandler(dataGridView_Resize);
62
63      //delegates for virtual mode
64      this.dataGridView.CellValueNeeded += new DataGridViewCellValueEventHandler(dataGridView_CellValueNeeded);
65      this.dataGridView.CellValuePushed += new DataGridViewCellValueEventHandler(dataGridView_CellValuePushed);
66      this.dataGridView.UserDeletingRow += new DataGridViewRowCancelEventHandler(dataGridView_UserDeletingRow);
67    }
68
69    private ColumnGroupView(ColumnGroup columnGroup)
70      : this() {
71      this.ColumnGroup = columnGroup;
72      this.ColumnGroup.Changed += this.ColumnGroupChanged;
73      this.dataGridView.ClearSelection();
74      this.state = ColumnGroupState.None;
75      this.UpdateDataGridView();
76    }
77
78    public ColumnGroupView(ColumnGroup columnGroup, CommandChain commandChain)
79      : this(columnGroup) {
80      this.commandChain = commandChain;
81    }
82
83    public bool ColumnGroupActive {
84      get { return this.ColumnGroup.Active; }
85      set {
86        this.ColumnGroup.Active = value;
87        if (this.ColumnGroup.Active)
88          this.txtColumnGroupName.BackColor = Color.LightGreen;
89        else {
90          this.dataGridView.ClearSelection();
91          this.txtColumnGroupName.BackColor = Control.DefaultBackColor;
92        }
93        UpdateStateInformation();
94      }
95    }
96
97    private ColumnGroup columnGroup;
98    public ColumnGroup ColumnGroup {
99      get { return (ColumnGroup)this.columnGroup; }
100      private set { this.columnGroup = value; }
101    }
102
103    private Data.Model.DataSet DataSet {
104      get { return ((DataSetView)this.Parent).DataSet; }
105    }
106
107    private CommandChain commandChain;
108    public CommandChain CommandChain {
109      get { return this.commandChain; }
110      set { this.commandChain = value; }
111    }
112
113    public bool AllowReorderColumns {
114      get { return this.dataGridView.AllowUserToOrderColumns; }
115      set { this.dataGridView.AllowUserToOrderColumns = value; }
116    }
117
118    public int[] DisplayIndexes {
119      get {
120        int[] ret = new int[this.ColumnGroup.Columns.Count()];
121        for (int i = 0; i < this.dataGridView.Columns.Count; i++) {
122          ret[dataGridView.Columns[i].DisplayIndex] = i;
123        }
124        return ret;
125      }
126    }
127
128    public int MaxWidth {
129      get { return this.MaximumSize.Width; }
130      set {
131        this.MaximumSize = new Size(value, this.MaximumSize.Height);
132        this.dataGridView.MaximumSize = new Size(value, this.MaximumSize.Height);
133        RecalculateWidthOfControl();
134      }
135    }
136
137    //IMPORTANT: use the defined property to change the state, because the event StateChanged must be fired!
138    private ColumnGroupState state;
139    public ColumnGroupState State {
140      get { return this.state; }
141      protected set {
142        this.state = value;
143        FireStateChanged();
144      }
145    }
146
147    public event EventHandler StateChanged;
148    protected void FireStateChanged() {
149      OnStateChanged();
150    }
151
152    protected virtual void OnStateChanged() {
153      if (StateChanged != null) {
154        StateChanged(this, new EventArgs());
155      }
156    }
157
158    public event ColumnGroupActivatedEventHandler Activated;
159    public void FireActivated(bool addToActiveColumnGroups) {
160      OnActivated(addToActiveColumnGroups);
161    }
162
163    protected virtual void OnActivated(bool addToActiveColumnGroups) {
164      if (Activated != null) {
165        Activated(this, addToActiveColumnGroups);
166      }
167    }
168
169    private void UpdateStateInformation() {
170      this.UpdateStateInformation(false);
171    }
172
173    private void UpdateStateInformation(bool selectionChanged) {
174      ColumnGroupState newState = this.ColumnGroupActive ? ColumnGroupState.Active : ColumnGroupState.None;
175      foreach (ColumnBase col in ColumnGroup.SelectedColumns) {
176        if (col is DoubleColumn)
177          newState |= ColumnGroupState.DoubleColumnSelected;
178        else if (col is StringColumn)
179          newState |= ColumnGroupState.StringColumnSelected;
180        else if (col is DateTimeColumn)
181          newState |= ColumnGroupState.DateTimeColumnSelected;
182        else if (col is ProgrammableColumn)
183          newState |= ColumnGroupState.ProgrammableColumnSelected;
184        if (col.ContainsNullValues)
185          newState |= ColumnGroupState.AnySelectedColumnContainsNull;
186      }
187      if (ColumnGroup.Sorted) {
188        if (ColumnGroup.SelectedColumns.Any(col => col.SortOrder == SortOrder.None))
189          newState |= ColumnGroupState.AnySelectedColumnNotSorted;
190        else
191          newState |= ColumnGroupState.Sorted;
192      }
193      if (newState != this.State || selectionChanged)
194        this.State = newState;
195    }
196
197    private void PasteClipboardContent() {
198      if (dataGridView.CurrentCell != null) {
199        string values = Clipboard.GetText();
200        values = values.Remove(values.Length - Environment.NewLine.Length);
201        this.commandChain.Add(new PasteValuesCommand(DataSet, this.ColumnGroup.Name, dataGridView.CurrentCell.ColumnIndex,
202          dataGridView.CurrentCell.RowIndex, values));
203      }
204    }
205
206    private void CopyClipboardContent() {
207      if (dataGridView.SelectedCells.Count != 0) {
208        StringBuilder s = new StringBuilder();
209        DataGridViewCell cell;
210        int minRowIndex = dataGridView.SelectedCells[0].RowIndex;
211        int maxRowIndex = dataGridView.SelectedCells[dataGridView.SelectedCells.Count - 1].RowIndex;
212        int minColIndex = dataGridView.SelectedCells[0].ColumnIndex;
213        int maxColIndex = dataGridView.SelectedCells[dataGridView.SelectedCells.Count - 1].ColumnIndex;
214
215        if (minRowIndex > maxRowIndex) {
216          int temp = minRowIndex;
217          minRowIndex = maxRowIndex;
218          maxRowIndex = temp;
219        }
220
221        if (minColIndex > maxColIndex) {
222          int temp = minColIndex;
223          minColIndex = maxColIndex;
224          maxColIndex = temp;
225        }
226        if (maxRowIndex == dataGridView.RowCount - 1)
227          maxRowIndex--;
228
229        for (int i = minRowIndex; i < maxRowIndex + 1; i++) {
230          for (int j = minColIndex; j < maxColIndex + 1; j++) {
231            cell = dataGridView[j, i];
232            if (cell.Selected) {
233              if (cell.Value != null)
234                s.Append(cell.Value.ToString());
235            }
236            if (j != maxColIndex)
237              s.Append("\t");
238          }
239          s.Append(Environment.NewLine);
240        }
241        Clipboard.SetText(s.ToString());
242      }
243    }
244
245    public override void Refresh() {
246      base.Refresh();
247      if (ColumnGroup != null) {
248        this.UpdateDataGridView();
249      } else {
250        dataGridView.ColumnCount = 0;
251        dataGridView.RowCount = 0;
252      }
253    }
254
255    public void ColumnGroupChanged(object sender, EventArgs e) {
256      this.UpdateDataGridView();
257    }
258
259    private void UpdateDataGridView() {
260      int firstVisibleRowIndex = 0;
261      int firstVisibleColIndex = 0;
262      if (dataGridView.FirstDisplayedCell != null) {
263        if (firstVisibleColIndex < ColumnGroup.Columns.Count())
264          firstVisibleColIndex = dataGridView.FirstDisplayedCell.ColumnIndex;
265        if (firstVisibleRowIndex < ColumnGroup.RowCount)
266          firstVisibleRowIndex = dataGridView.FirstDisplayedCell.RowIndex;
267      }
268
269      //needed because otherwise columns could not be added
270      this.dataGridView.SelectionMode = DataGridViewSelectionMode.RowHeaderSelect;
271      if (dataGridView.ColumnCount != ColumnGroup.Columns.Count()) {
272        this.dataGridView.ColumnCount = ColumnGroup.Columns.Count();
273        for (int i = 0; i < ColumnGroup.Columns.Count(); i++) {
274          dataGridView.Columns[i].SortMode = DataGridViewColumnSortMode.Programmatic;
275        }
276      }
277      for (int i = 0; i < ColumnGroup.Columns.Count(); i++)
278        dataGridView.Columns[i].HeaderText = ColumnGroup.Columns.ElementAt(i).ToString().Insert(ColumnGroup.Columns.ElementAt(i).ToString().IndexOf('<'), "\n");
279
280      // needed for performance reasons; further information at http://whiletrue.nl/blog/?p=38
281      if (dataGridView.RowCount != ColumnGroup.RowCount + (ColumnGroup.Columns.Count() == 0 ? 0 : 1)) {
282        //event handler must be deregistered cause otherwise cellvaluepushed is fired again
283        this.dataGridView.CellValuePushed -= new DataGridViewCellValueEventHandler(dataGridView_CellValuePushed);
284        if (Math.Abs(dataGridView.RowCount - ColumnGroup.RowCount) > 10)
285          dataGridView.Rows.Clear();
286        bool rowAdded = dataGridView.RowCount == ColumnGroup.RowCount && dataGridView.RowCount != 0;
287        dataGridView.RowCount = ColumnGroup.RowCount + (!ColumnGroup.Columns.Any() ? 0 : 1);
288
289        if (rowAdded) {
290          Point p = this.dataGridView.CurrentCellAddress;
291          p.Y += 1;
292          this.dataGridView.CurrentCell = this.dataGridView.Rows[p.Y].Cells[p.X];
293          this.dataGridView.ClearSelection();
294          this.dataGridView.CurrentCell.Selected = true;
295        }
296        this.dataGridView.CellValuePushed += new DataGridViewCellValueEventHandler(dataGridView_CellValuePushed);
297      }
298
299      UpdateDataGridViewHeaderCells();
300      this.dataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells);
301      this.dataGridView.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders);
302      if (dataGridView.RowCount != 0 && dataGridView.ColumnCount != 0) {
303        if (firstVisibleColIndex >= dataGridView.ColumnCount)
304          firstVisibleColIndex = 0;
305        if (firstVisibleRowIndex >= dataGridView.RowCount)
306          firstVisibleRowIndex = 0;
307        dataGridView.FirstDisplayedCell = dataGridView[firstVisibleColIndex, firstVisibleRowIndex];
308      }
309
310      UpdateSortGlyph();
311      this.txtColumnGroupName.Text = this.ColumnGroup.Name + "  " + ColumnGroup.RowCount + " rows";
312      RecalculateWidthOfControl();
313      this.dataGridView.Invalidate();
314      UpdateStateInformation();
315    }
316
317    private void UpdateDataGridViewHeaderCells() {
318      int index = dataGridView.FirstDisplayedScrollingRowIndex;
319      if (index == -1) index = 0;
320      int updatedRows = 0;
321      int count = dataGridView.DisplayedRowCount(true);
322
323      while (updatedRows < count) {
324        dataGridView.Rows[index].HeaderCell.Value = (index + 1).ToString();
325        if (dataGridView.Rows[index].Visible)
326          updatedRows++;
327        index++;
328      }
329    }
330
331    private void dataGridView_ColumnHeaderMouseClick(object sender, System.Windows.Forms.DataGridViewCellMouseEventArgs e) {
332      if (e.Button == MouseButtons.Right) {
333        this.commandChain.Add(new SortCommand(DataSet, this.ColumnGroup.Name,
334          e.ColumnIndex, (Control.ModifierKeys & Keys.Control) == Keys.Control));
335        //this.UpdateSortGlyph();
336        //this.dataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells);
337        //UpdateStateInformation();
338      }
339    }
340
341    private void dataGridView_ColumnHeaderMouseDoubleClick(object sender, System.Windows.Forms.DataGridViewCellMouseEventArgs e) {
342      if (e.Button == MouseButtons.Left) {
343        dataGridView.ClearSelection();
344        Rectangle rect = dataGridView.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true);
345        ColumnBase col = this.ColumnGroup.Columns.ElementAt(e.ColumnIndex);
346        txtColumnName.Text = col.Name;
347        txtColumnName.Size = rect.Size;
348        txtColumnName.Location = rect.Location;
349        txtColumnName.Visible = true;
350        txtColumnName.Focus();
351        txtColumnName.BringToFront();
352      }
353    }
354
355    private void UpdateSortGlyph() {
356      System.Collections.IEnumerator e = this.dataGridView.Columns.GetEnumerator();
357      e.MoveNext();
358      foreach (SortOrder sortOrder in this.ColumnGroup.SortOrdersForColumns) {
359        ((DataGridViewColumn)e.Current).HeaderCell.SortGlyphDirection = sortOrder;
360        e.MoveNext();
361      }
362    }
363
364    private void dataGridView_SelectionChanged(object sender, EventArgs e) {
365      int nullValuesCount = 0;
366      int totalValuesCount = 0;
367      IComparable minimum = "";
368      IComparable maximum = "";
369      double? mean = null;
370      double? median = null;
371      double? stddev = null;
372      ColumnBase column;
373
374      this.ColumnGroup.ClearSelectedColumns();
375      if (this.dataGridView.SelectedColumns.Count != 0) {
376        foreach (DataGridViewColumn col in this.dataGridView.SelectedColumns) {
377          column = this.ColumnGroup.Columns.ElementAt(col.Index);
378          column.Selected = true;
379          nullValuesCount += column.NullValuesCount;
380          totalValuesCount += column.NonNullValuesCount;
381        }
382        if (this.dataGridView.SelectedColumns.Count == 1) {
383          column = this.ColumnGroup.Columns.ElementAt(dataGridView.SelectedColumns[0].Index);
384          minimum = column.Minimum;
385          maximum = column.Maximum;
386          if (column is DoubleColumn) {
387            mean = ((DoubleColumn)column).Mean;
388            stddev = ((DoubleColumn)column).StandardDeviation;
389            median = ((DoubleColumn)column).Median;
390          }
391        }
392      }
393      lblNullValues.Text = nullValuesCount.ToString();
394      double nullPercentage = (100.0 / (double)(totalValuesCount + nullValuesCount)) * (double)nullValuesCount;
395      lblNullPercentage.Text = Double.IsNaN(nullPercentage) ? "" : nullPercentage.ToString();
396      lblValues.Text = totalValuesCount.ToString();
397      lblMinimum.Text = minimum == null ? "" : minimum.ToString();
398      lblMaximum.Text = maximum == null ? "" : maximum.ToString();
399      lblMean.Text = mean == null ? "" : mean.ToString();
400      lblStdDev.Text = stddev == null ? "" : stddev.ToString();
401      lblMedian.Text = median == null ? "" : median.ToString();
402      UpdateStateInformation(true);
403    }
404
405    private void dataGridView_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e) {
406      RecalculateWidthOfControl();
407    }
408
409    private void RecalculateWidthOfControl() {
410      int width = 0;
411      foreach (DataGridViewColumn col in this.dataGridView.Columns)
412        width += col.Width;
413      //no columns in datagrid
414      if (width != 0) {
415        width += this.dataGridView.RowHeadersWidth;
416        //datagridview.controls[1] is always the vertical scrollbar
417        if (dataGridView.Controls[1].Visible)
418          width += 20;
419      }
420      this.dataGridView.Width = width;
421      this.Width = width;
422    }
423
424    private void dataGridView_MouseClick(object sender, MouseEventArgs e) {
425      this.ColumnGroupActive = true;
426      this.FireActivated(false);
427
428      if (this.dataGridView.AllowUserToOrderColumns || e.Clicks >= 2)
429        return;
430
431      System.Windows.Forms.DataGridView.HitTestInfo hit = dataGridView.HitTest(e.X, e.Y);
432      // row header click
433      if (hit.ColumnIndex == -1 && hit.RowIndex >= 0) {
434        if (e.Button == MouseButtons.Right) {
435          this.commandChain.Add(new InsertRowCommand(DataSet, this.ColumnGroup.Name, hit.RowIndex));
436        } else {
437          if (dataGridView.SelectionMode != DataGridViewSelectionMode.RowHeaderSelect)
438            dataGridView.SelectionMode = DataGridViewSelectionMode.RowHeaderSelect;
439        }
440      } // column header click
441      else if (hit.RowIndex == -1 && hit.ColumnIndex >= 0 && e.Button == MouseButtons.Left) {
442        if (dataGridView.SelectionMode != DataGridViewSelectionMode.ColumnHeaderSelect)
443          dataGridView.SelectionMode = DataGridViewSelectionMode.ColumnHeaderSelect;
444      }
445    }
446
447    private void dataGridView_AllowUserToOrderColumnsChanged(object sender, EventArgs e) {
448      if (this.dataGridView.AllowUserToOrderColumns)
449        this.dataGridView.SelectionMode = DataGridViewSelectionMode.RowHeaderSelect;
450    }
451
452    private void dataGridView_KeyDown(object sender, KeyEventArgs e) {
453      //handle deletion of columns and emptying of cells
454      if (e.KeyCode == Keys.Delete) {
455        if (this.dataGridView.SelectedColumns.Count != 0)
456          this.commandChain.Add(new DeleteColumnCommand(DataSet, this.ColumnGroup.Name, ColumnGroup.SelectedColumnIndexes));
457        else if (this.dataGridView.SelectedRows.Count != 0) {
458          //to ensure that cells are not emptied before the rows got deleted
459          //deleting of rows handled by user deleting rows
460        } else if (this.dataGridView.SelectedCells.Count != 0) {
461          List<Point> cells = new List<Point>();
462          foreach (DataGridViewCell cell in this.dataGridView.SelectedCells) {
463            if (cell.RowIndex < this.ColumnGroup.Columns.ElementAt(cell.ColumnIndex).TotalValuesCount && cell.Value != null)
464              cells.Add(new Point(cell.ColumnIndex, cell.RowIndex));
465          }
466          if (cells.Count != 0)
467            this.commandChain.Add(new ChangeValuesToNullCommand(DataSet, this.ColumnGroup.Name, cells));
468        }
469      }
470        //handle paste of values
471      else if (e.Control && e.KeyCode == Keys.V)
472        PasteClipboardContent();
473      else if (e.Control && e.KeyCode == Keys.C)
474        CopyClipboardContent();
475    }
476
477    private void dataGridView_RowHeadersWidthChanged(object sender, EventArgs e) {
478      this.RecalculateWidthOfControl();
479    }
480
481    private void dataGridView_CellMouseEnter(object sender, DataGridViewCellEventArgs e) {
482      if (e.RowIndex == -1 && e.ColumnIndex != -1) {
483        toolTip.SetToolTip(this.dataGridView, ToExcelColumnIndex(e.ColumnIndex));
484      } else if (toolTip.Active) {
485        toolTip.RemoveAll();
486      }
487    }
488
489    private void dataGridView_Resize(object sender, EventArgs e) {
490      UpdateDataGridViewHeaderCells();
491    }
492
493    private void dataGridView_Scroll(object sender, ScrollEventArgs e) {
494      if (e.ScrollOrientation == ScrollOrientation.VerticalScroll)
495        UpdateDataGridViewHeaderCells();
496    }
497
498    private string ToExcelColumnIndex(int index) {
499      //if (symb.Length == 1) {       // 'A' .. 'Z'
500      //  return TryTranslateColumnIndexDigit(symb[0], out columnIndex);
501      //} else if (symb.Length == 2) { // 'AA' ... 'ZZ'
502      //  bool ok;
503      //  int d0, d1;
504      //  ok = TryTranslateColumnIndexDigit(symb[0], out d1) & TryTranslateColumnIndexDigit(symb[1], out d0);
505      //  columnIndex = (d1 + 1) * 26 + d0;
506      //  return ok;
507      //} else {
508      //  columnIndex = 0;
509      //  return false;
510      //}
511      #region digits
512      var digits = new char[] {
513        '#',
514        'A',
515        'B',
516        'C',
517        'D',
518        'E',
519        'F',
520        'G',
521        'H',
522        'I',
523        'J',
524        'K',
525        'L',
526        'M',
527        'N',
528        'O',
529        'P',
530        'Q',
531        'R',
532        'S',
533        'T',
534        'U',
535        'V',
536        'W',
537        'X',
538        'Y',
539        'Z'};
540      int b = digits.Length - 1;
541      #endregion
542      string excelIndex = string.Empty;
543      index = index + 1;
544      while (index > 0) {
545        int d = index / b;
546        int rem = index % b;
547        index = d;
548        excelIndex = digits[rem] + excelIndex;
549      }
550      return excelIndex;
551    }
552
553    #region DataGridView virtual mode event handler
554    private void dataGridView_CellValueNeeded(object sender, System.Windows.Forms.DataGridViewCellValueEventArgs e) {
555      e.Value = ColumnGroup.Columns.ElementAt(e.ColumnIndex).GetValue(e.RowIndex);
556    }
557
558    private void dataGridView_CellValuePushed(object sender, System.Windows.Forms.DataGridViewCellValueEventArgs e) {
559      IComparable value = null;
560      try {
561        if (e.Value == null)
562          value = null;
563        else if (this.ColumnGroup.Columns.ElementAt(e.ColumnIndex).DataType == typeof(double?))
564          value = double.Parse((string)e.Value);
565        else if (this.ColumnGroup.Columns.ElementAt(e.ColumnIndex).DataType == typeof(DateTime?))
566          value = DateTime.Parse((string)e.Value);
567        else
568          value = e.Value.ToString();
569      }
570      catch (FormatException) {
571      }
572
573      if (e.RowIndex == this.dataGridView.RowCount - 1) {
574        IComparable[] row = new IComparable[this.ColumnGroup.Columns.Count()];
575        row[e.ColumnIndex] = value;
576        this.commandChain.Add(new AddRowCommand(this.DataSet, this.ColumnGroup.Name, row));
577      } else {
578        this.commandChain.Add(new ChangeValueCommand(this.DataSet, this.ColumnGroup.Name, e.ColumnIndex, e.RowIndex, value));
579      }
580    }
581
582    private void dataGridView_UserDeletingRow(object sender, System.Windows.Forms.DataGridViewRowCancelEventArgs e) {
583      e.Cancel = true;
584      if (e.Row.Index < this.ColumnGroup.RowCount) {
585        List<int> positions;
586        if (this.dataGridView.AreAllCellsSelected(true))
587          positions = Enumerable.Range(0, this.ColumnGroup.RowCount).ToList();
588        else {
589          positions = new List<int>();
590          for (int i = 0; i < this.dataGridView.SelectedRows.Count; i++)
591            if (this.dataGridView.SelectedRows[i].Index < this.ColumnGroup.RowCount)
592              positions.Add(this.dataGridView.SelectedRows[i].Index);
593          positions.Sort();
594        }
595        if (positions.Count != 0) {
596          this.commandChain.Add(new DeleteRowsCommand(DataSet, this.ColumnGroup.Name, positions));
597        }
598        this.dataGridView.ClearSelection();
599      }
600    }
601    #endregion
602
603    #region txtColumnName event handler
604    private void txtColumnName_Leave(object source, EventArgs e) {
605      this.txtColumnName.Visible = false;
606    }
607
608    private void txtColumnName_KeyDown(object source, KeyEventArgs e) {
609      if (e.KeyCode != Keys.Enter && e.KeyCode != Keys.Escape)
610        return;
611      if (e.KeyCode == Keys.Enter) {
612        DataGridView.HitTestInfo h = this.dataGridView.HitTest(txtColumnName.Location.X, txtColumnName.Location.Y);
613        this.commandChain.Add(new RenameColumnCommand(DataSet, this.ColumnGroup.Name, h.ColumnIndex, txtColumnName.Text));
614      }
615      this.txtColumnName.Visible = false;
616    }
617    #endregion
618
619    #region txtColumnGroupName event handler
620    private void txtColumnGroupName_Click(object sender, EventArgs e) {
621      bool ctrlPressed = (Control.ModifierKeys & Keys.Control) == Keys.Control;
622      this.dataGridView.ClearSelection();
623      this.ColumnGroupActive = !this.ColumnGroupActive;
624      FireActivated(ctrlPressed);
625      UpdateStateInformation();
626    }
627
628    private void txtColumnGroupName_DoubleClick(object sender, EventArgs e) {
629      txtColumnGroupName.ReadOnly = false;
630      txtColumnGroupName.Text = ColumnGroup.Name;
631    }
632
633    private void txtColumnGroupName_Leave(object sender, EventArgs e) {
634      if (!txtColumnGroupName.ReadOnly) {
635        txtColumnGroupName.ReadOnly = true;
636        if (CheckIfNewColumnGroupNameIsAllowed(txtColumnGroupName.Text))
637          this.commandChain.Add(new RenameColumnGroupCommand(DataSet, this.ColumnGroup.Name, txtColumnGroupName.Text));
638      }
639    }
640
641    private void txtColumnGroupName_KeyDown(object sender, KeyEventArgs e) {
642      if (this.txtColumnGroupName.ReadOnly) //user can not change the name if it is readonly
643        return;
644      if (e.KeyCode != Keys.Enter && e.KeyCode != Keys.Escape)
645        return;
646      if (e.KeyCode == Keys.Enter && CheckIfNewColumnGroupNameIsAllowed(txtColumnGroupName.Text)) {
647        this.commandChain.Add(new RenameColumnGroupCommand(DataSet, this.ColumnGroup.Name, txtColumnGroupName.Text));
648      }
649      txtColumnGroupName.ReadOnly = true;
650      this.Focus();
651      this.Refresh();
652    }
653
654    private bool CheckIfNewColumnGroupNameIsAllowed(string newName) {
655      return !this.DataSet.ColumnGroups.Any(cg => cg.Name == newName);
656    }
657    #endregion
658  }
659}
Note: See TracBrowser for help on using the repository browser.