Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 7267 was 7267, checked in by gkronber, 12 years ago

#1734 updated copyright year in all files of the DataImporter branch

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