Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 7652 was 7652, checked in by mkommend, 12 years ago

#1804: improved responsiveness of DataImporter during scroll operations.

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