Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 7730 was 7730, checked in by sforsten, 12 years ago

#1818: the updating of the row headers is now done in the event CellFormatting of the DataGridView, which increases the performance

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