Free cookie consent management tool by TermsFeed Policy Generator

source: branches/MemPRAlgorithm/HeuristicLab.Data.Views/3.3/StringConvertibleArrayView.cs @ 14429

Last change on this file since 14429 was 14299, checked in by gkronber, 8 years ago

#2674: also added row names to clipboard for StringConvertibleArrays (the code for copying to clipboard was irrelevant anyway because C&P was not disabled for the DataViewGrid)

File size: 9.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.ComponentModel;
24using System.Drawing;
25using System.Linq;
26using System.Text;
27using System.Windows.Forms;
28using HeuristicLab.Common;
29using HeuristicLab.MainForm;
30using HeuristicLab.MainForm.WindowsForms;
31
32namespace HeuristicLab.Data.Views {
33  [View("StringConvertibleArray View")]
34  [Content(typeof(IStringConvertibleArray), true)]
35  public partial class StringConvertibleArrayView : AsynchronousContentView {
36    public new IStringConvertibleArray Content {
37      get { return (IStringConvertibleArray)base.Content; }
38      set { base.Content = value; }
39    }
40
41    public override bool ReadOnly {
42      get {
43        if ((Content != null) && Content.ReadOnly) return true;
44        return base.ReadOnly;
45      }
46      set { base.ReadOnly = value; }
47    }
48
49    public StringConvertibleArrayView() {
50      InitializeComponent();
51      errorProvider.SetIconAlignment(lengthTextBox, ErrorIconAlignment.MiddleLeft);
52      errorProvider.SetIconPadding(lengthTextBox, 2);
53    }
54
55    protected override void DeregisterContentEvents() {
56      Content.ElementNamesChanged -= new EventHandler(Content_ElementNamesChanged);
57      Content.ItemChanged -= new EventHandler<EventArgs<int>>(Content_ItemChanged);
58      Content.Reset -= new EventHandler(Content_Reset);
59      base.DeregisterContentEvents();
60    }
61
62    protected override void RegisterContentEvents() {
63      base.RegisterContentEvents();
64      Content.ItemChanged += new EventHandler<EventArgs<int>>(Content_ItemChanged);
65      Content.Reset += new EventHandler(Content_Reset);
66      Content.ElementNamesChanged += new EventHandler(Content_ElementNamesChanged);
67    }
68
69    protected override void OnContentChanged() {
70      base.OnContentChanged();
71      if (Content == null) {
72        lengthTextBox.Text = "";
73        dataGridView.Rows.Clear();
74        dataGridView.Columns.Clear();
75      } else
76        UpdateData();
77    }
78
79    protected override void SetEnabledStateOfControls() {
80      base.SetEnabledStateOfControls();
81      lengthTextBox.Enabled = Content != null;
82      dataGridView.Enabled = Content != null;
83      lengthTextBox.ReadOnly = ReadOnly || (Content != null && !Content.Resizable);
84      dataGridView.ReadOnly = ReadOnly;
85    }
86
87    private void UpdateData() {
88      lengthTextBox.Text = Content.Length.ToString();
89      lengthTextBox.Enabled = true;
90      dataGridView.Rows.Clear();
91      dataGridView.Columns.Clear();
92      if (Content.Length > 0) {
93        dataGridView.ColumnCount++;
94        dataGridView.Columns[0].FillWeight = float.Epsilon;  // sum of all fill weights must not be larger than 65535
95        dataGridView.RowCount = Content.Length;
96        for (int i = 0; i < Content.Length; i++) {
97          dataGridView.Rows[i].Cells[0].Value = Content.GetValue(i);
98        }
99        dataGridView.Columns[0].Width = dataGridView.Columns[0].GetPreferredWidth(DataGridViewAutoSizeColumnMode.AllCells, true);
100      }
101      UpdateRowHeaders();
102      dataGridView.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders);
103      dataGridView.Enabled = true;
104    }
105
106    public virtual void UpdateRowHeaders() {
107      int i = 0;
108      foreach (string elementName in Content.ElementNames) {
109        dataGridView.Rows[i].HeaderCell.Value = elementName;
110        i++;
111      }
112      for (; i < dataGridView.RowCount; i++) {
113        dataGridView.Rows[i].HeaderCell.Value = string.Empty;
114      }
115    }
116
117    private void Content_ElementNamesChanged(object sender, EventArgs e) {
118      if (InvokeRequired)
119        Invoke(new EventHandler(Content_ElementNamesChanged), sender, e);
120      else
121        UpdateRowHeaders();
122    }
123
124    private void Content_ItemChanged(object sender, EventArgs<int> e) {
125      if (InvokeRequired)
126        Invoke(new EventHandler<EventArgs<int>>(Content_ItemChanged), sender, e);
127      else {
128        // if a resize of the array occurs and some other class handles the event and provides default values
129        //then the itemChanged will occur before the reset event. hence the check was added
130        if (dataGridView.RowCount <= e.Value) return;
131        dataGridView.Rows[e.Value].Cells[0].Value = Content.GetValue(e.Value);
132        Size size = dataGridView.Rows[e.Value].Cells[0].PreferredSize;
133        dataGridView.Columns[0].Width = Math.Max(dataGridView.Columns[0].Width, size.Width);
134      }
135    }
136    private void Content_Reset(object sender, EventArgs e) {
137      if (InvokeRequired)
138        Invoke(new EventHandler(Content_Reset), sender, e);
139      else
140        UpdateData();
141    }
142
143    #region TextBox Events
144    private void lengthTextBox_Validating(object sender, CancelEventArgs e) {
145      int i = 0;
146      if (!int.TryParse(lengthTextBox.Text, out i) || (i < 0)) {
147        e.Cancel = true;
148        errorProvider.SetError(lengthTextBox, "Invalid Array Length (Valid Values: Positive Integers Larger or Equal to 0)");
149        lengthTextBox.SelectAll();
150      }
151    }
152    private void lengthTextBox_Validated(object sender, EventArgs e) {
153      if (!Content.ReadOnly) Content.Length = int.Parse(lengthTextBox.Text);
154      errorProvider.SetError(lengthTextBox, string.Empty);
155    }
156    private void lengthTextBox_KeyDown(object sender, KeyEventArgs e) {
157      if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
158        lengthLabel.Focus();  // set focus on label to validate data
159      if (e.KeyCode == Keys.Escape) {
160        lengthTextBox.Text = Content.Length.ToString();
161        lengthLabel.Focus();  // set focus on label to validate data
162      }
163    }
164    #endregion
165
166    #region DataGridView Events
167    private void dataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) {
168      string errorMessage;
169      if (Content != null && !Content.Validate(e.FormattedValue.ToString(), out errorMessage)) {
170        e.Cancel = true;
171        dataGridView.Rows[e.RowIndex].ErrorText = errorMessage;
172      }
173    }
174    private void dataGridView_CellParsing(object sender, DataGridViewCellParsingEventArgs e) {
175      string value = e.Value.ToString();
176      e.ParsingApplied = Content.SetValue(value, e.RowIndex);
177      if (e.ParsingApplied) e.Value = Content.GetValue(e.RowIndex);
178    }
179    private void dataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e) {
180      dataGridView.Rows[e.RowIndex].ErrorText = string.Empty;
181    }
182    private void dataGridView_KeyDown(object sender, KeyEventArgs e) {
183      if (!ReadOnly && e.Control && e.KeyCode == Keys.V)
184        PasteValuesToDataGridView();
185      else if (e.Control && e.KeyCode == Keys.C)
186        CopyValuesFromDataGridView();
187      else if (e.Control && e.KeyCode == Keys.A)
188        dataGridView.SelectAll();
189    }
190    private void CopyValuesFromDataGridView() {
191      if (dataGridView.SelectedCells.Count == 0) return;
192      StringBuilder s = new StringBuilder();
193      int minRowIndex = dataGridView.SelectedCells[0].RowIndex;
194      int maxRowIndex = dataGridView.SelectedCells[dataGridView.SelectedCells.Count - 1].RowIndex;
195
196      if (minRowIndex > maxRowIndex) {
197        int temp = minRowIndex;
198        minRowIndex = maxRowIndex;
199        maxRowIndex = temp;
200      }
201
202      for (int i = minRowIndex; i <= maxRowIndex; i++) {
203        DataGridViewColumn column = dataGridView.Columns.GetFirstColumn(DataGridViewElementStates.Visible);
204        DataGridViewCell cell = dataGridView[column.Index, i];
205        if (cell.Selected) {
206          s.Append(Content.ElementNames.ElementAt(i));
207          s.Append("\t");
208          s.Append(Content.GetValue(i));
209          s.Append(Environment.NewLine);
210        }
211      }
212      Clipboard.SetText(s.ToString());
213    }
214    private void PasteValuesToDataGridView() {
215      string[] values = SplitClipboardString(Clipboard.GetText());
216      int rowIndex = 0;
217      if (dataGridView.CurrentCell != null)
218        rowIndex = dataGridView.CurrentCell.RowIndex;
219
220      if (Content.Length < rowIndex + values.Length) Content.Length = rowIndex + values.Length;
221      for (int row = 0; row < values.Length; row++)
222        Content.SetValue(values[row], row + rowIndex);
223    }
224    private string[] SplitClipboardString(string clipboardText) {
225      if (clipboardText.EndsWith(Environment.NewLine))
226        clipboardText = clipboardText.Remove(clipboardText.Length - Environment.NewLine.Length);  //remove last newline constant
227      return clipboardText.Split(new string[] { Environment.NewLine, "\t" }, StringSplitOptions.None);
228    }
229    #endregion
230  }
231}
Note: See TracBrowser for help on using the repository browser.