public static void ColumnMassEdit(object sender, DBTableControl.DBEditorTableControl mainTable) { DataGridColumn col = (((sender as MenuItem).Parent as ContextMenu).PlacementTarget as DataGridColumnHeader).Column; string colname = (string)col.Header; InputBox stringeditbox = new InputBox(); stringeditbox.Input = "{cell}"; stringeditbox.ShowDialog(); if (stringeditbox.DialogResult == System.Windows.Forms.DialogResult.OK) { int datacolindex = mainTable.CurrentTable.Columns.IndexOf(colname); for (int i = 0; i < mainTable.CurrentTable.Rows.Count; i++) { // Make sure our visible rows are up to date and skip any currently filtered rows. if (mainTable._visibleRows.Count <= mainTable.CurrentTable.Rows.Count) { mainTable.UpdateVisibleRows(); } if (mainTable._visibleRows[i] == System.Windows.Visibility.Collapsed) { continue; } mainTable.CurrentTable.Rows[i][datacolindex] = stringeditbox.Input.Replace("{cell}", mainTable.CurrentTable.Rows[i][datacolindex].ToString()); // Refresh the cell in the UI, using its visual coordinates. mainTable.RefreshCell(mainTable.dbDataGrid.Items.IndexOf(mainTable.CurrentTable.DefaultView[i]), mainTable.dbDataGrid.Columns.IndexOf(col)); } } }
public static void ClearAllHiddenMenuItem(DBTableControl.DBEditorTableControl mainTable) { //Prompt for confirmation. string text = "Are you sure you want to clear all saved hidden column information?"; string caption = "Clear Confirmation"; MessageBoxButton button = MessageBoxButton.YesNo; MessageBoxImage image = MessageBoxImage.Question; MessageBoxResult result = MessageBox.Show(text, caption, button, image); if (result == MessageBoxResult.Yes) { // Clear internal list. mainTable._hiddenColumns.Clear(); // Clear saved list. mainTable._savedconfig.HiddenColumns.Clear(); } mainTable.UpdateConfig(); if (mainTable.ShowAllColumns) { mainTable.Refresh(); } }
public static void DataGridMassEditStringsMenuItem(object sender, DBTableControl.DBEditorTableControl mainTable) { InputBox stringeditbox = new InputBox(); stringeditbox.Input = "{cell}"; stringeditbox.ShowDialog(); if (stringeditbox.DialogResult == System.Windows.Forms.DialogResult.OK) { int datarowindex = -1; int datacolindex = -1; foreach (DataGridCellInfo cellinfo in mainTable.dbDataGrid.SelectedCells.Where(n => n.Item is DataRowView)) { datarowindex = mainTable.CurrentTable.Rows.IndexOf((cellinfo.Item as DataRowView).Row); datacolindex = mainTable.CurrentTable.Columns.IndexOf((string)cellinfo.Column.Header); // Make sure our visible rows are up to date and skip any currently filtered rows. if (mainTable._visibleRows.Count <= mainTable.CurrentTable.Rows.Count) { mainTable.UpdateVisibleRows(); } if (mainTable._visibleRows[datarowindex] == System.Windows.Visibility.Collapsed) { continue; } mainTable.CurrentTable.Rows[datarowindex][datacolindex] = stringeditbox.Input.Replace("{cell}", mainTable.CurrentTable.Rows[datarowindex][datacolindex].ToString()); // Refresh the cell in the UI, using its visual coordinates. mainTable.RefreshCell(mainTable.dbDataGrid.Items.IndexOf(cellinfo.Item), mainTable.dbDataGrid.Columns.IndexOf(cellinfo.Column)); } } }
public static void RemoveSorting(object sender, DBTableControl.DBEditorTableControl mainTable) { DataGridColumn col = (((sender as MenuItem).Parent as ContextMenu).PlacementTarget as DataGridColumnHeader).Column; col.SortDirection = null; mainTable.Refresh(); }
public static void DataGridRevertCellMenuItem(object sender, DBTableControl.DBEditorTableControl mainTable) { foreach (DataGridCellInfo cellinfo in mainTable.dbDataGrid.SelectedCells.Where(n => n.Item is DataRowView)) { // Ignore added or detached cells since they have no original values and will instead throw an error. if ((cellinfo.Item as DataRowView).Row.RowState == DataRowState.Detached || (cellinfo.Item as DataRowView).Row.RowState == DataRowState.Added) { continue; } int datarowindex = mainTable.CurrentTable.Rows.IndexOf((cellinfo.Item as DataRowView).Row); int datacolindex = mainTable.CurrentTable.Columns.IndexOf((string)cellinfo.Column.Header); // Make sure our visible rows are up to date and skip any currently filtered rows. if (mainTable._visibleRows.Count <= mainTable.CurrentTable.Rows.Count) { mainTable.UpdateVisibleRows(); } if (mainTable._visibleRows[datarowindex] == System.Windows.Visibility.Collapsed) { continue; } mainTable.CurrentTable.Rows[datarowindex][datacolindex] = mainTable.CurrentTable.Rows[datarowindex][datacolindex, DataRowVersion.Original]; } }
public static void RowHeaderInsertRow(object sender, DBTableControl.DBEditorTableControl mainTable) { if (!mainTable.ReadOnly && sender is MenuItem) { // Double check that whant triggered the event is what we expect. if ((sender as MenuItem).DataContext is DataRowView) { // Determine visual and data index of calling row. int datarowindex = mainTable.dbDataGrid.Items.IndexOf(((sender as MenuItem).DataContext as DataRowView)); mainTable.InsertRow(datarowindex); } else { // We'll end up here if the user is attempting to insert a row in front of the blank row, so we will simply add a new row // at the end of the table, still we'll use a try block in case something unforseen happens. try { mainTable.InsertRow(); } catch (Exception ex) { #if DEBUG ErrorDialog.ShowDialog(ex); #endif } } } }
public static void UpdateVisibleRows(DBTableControl.DBEditorTableControl mainTable, IList <DBFilter> filterList, FilterSettings filterSettings) { for (int i = 0; i < mainTable.CurrentTable.Rows.Count; i++) { if (i >= mainTable._visibleRows.Count) { // We have a problem. Append additional items until we are ok again. while (i >= mainTable._visibleRows.Count) { mainTable._visibleRows.Add(System.Windows.Visibility.Visible); } } // If there are more rows in the datagrid than currentTable we are adding a new row by modifying the blank row, so // we should add rows to the list until we max out. while (mainTable.dbDataGrid.Items.Count > mainTable._visibleRows.Count) { mainTable._visibleRows.Add(System.Windows.Visibility.Visible); } if (FilterTestRow(i, mainTable, filterList, filterSettings)) { mainTable._visibleRows[i] = System.Windows.Visibility.Visible; } else { mainTable._visibleRows[i] = System.Windows.Visibility.Collapsed; } } }
public static void RowHeaderInsertManyRows(object sender, DBTableControl.DBEditorTableControl mainTable) { if (!mainTable.ReadOnly && sender is MenuItem) { // Request how many rows should be inserted from the user. InputBox insertrowsInputBox = new InputBox(); insertrowsInputBox.ShowDialog(); // Double check that whant triggered the event is what we expect. if (insertrowsInputBox.DialogResult == System.Windows.Forms.DialogResult.OK) { // Determine how many rows the user wants to add. int numrows = 0; try { numrows = int.Parse(insertrowsInputBox.Input); } catch (Exception ex) { if (ex is FormatException) { MessageBox.Show(String.Format("Input: {0}, is not a valid number of rows, please enter a whole number.", insertrowsInputBox.Input)); } else { #if DEBUG ErrorDialog.ShowDialog(ex); #endif } } for (int i = 0; i < numrows; i++) { DataRow newrow = mainTable.CurrentTable.NewRow(); if ((sender as MenuItem).DataContext is DataRowView) { mainTable.InsertRow(i); } else { try { // If the blank row is calling us, add to the end of the table. mainTable.InsertRow(); } catch (Exception ex) { #if DEBUG ErrorDialog.ShowDialog(ex); #endif } } } mainTable.UpdateVisibleRows(); mainTable.dbDataGrid.Items.Refresh(); } } }
private static bool PasteMatchesSelection(DBTableControl.DBEditorTableControl mainTable, string clipboardData) { // Build a blank clipboard copy from selected cells to compare to clipboardData string testSelection = ""; for (int i = 0; i < mainTable.CurrentTable.Rows.Count; i++) { // Additional error checking for the visibleRows internal list. if (i >= mainTable._visibleRows.Count) { mainTable.UpdateVisibleRows(); } // Ignore collapsed (filtered) rows when building our test string. if (mainTable._visibleRows[i] == System.Windows.Visibility.Collapsed) { continue; } bool writeEndofLine = false; int minColumnIndex = mainTable.dbDataGrid.SelectedCells.Min(n => n.Column.DisplayIndex); int maxColumnIndex = mainTable.dbDataGrid.SelectedCells.Max(n => n.Column.DisplayIndex); foreach (DataGridCellInfo cellinfo in mainTable.dbDataGrid.SelectedCells.Where(n => mainTable.CurrentTable.Rows.IndexOf((n.Item as DataRowView).Row) == i)) { for (int j = minColumnIndex; j < maxColumnIndex; j++) { testSelection += "\t"; } writeEndofLine = true; break; } if (writeEndofLine) { testSelection += "\r\n"; } } // If the number of lines don't match return false if (testSelection.Count(n => n == '\n') != clipboardData.Count(n => n == '\n')) { return(false); } // If the number of lines match, test each line for the same number of 'cells' foreach (string line in clipboardData.Split('\n')) { if (testSelection.Count(n => n == '\t') != clipboardData.Count(n => n == '\t')) { return(false); } } return(true); }
public FindReplaceHelper(DBTableControl.DBEditorTableControl mainTable) { _parentDbEdtiorTable = mainTable; // Register for FindAndReplaceWindowEvents _findReplaceWindow = new FindAndReplaceWindow(); _findReplaceWindow.FindNext += new EventHandler(findWindow_FindNext); _findReplaceWindow.FindAll += new EventHandler(findReplaceWindow_FindAll); _findReplaceWindow.Replace += new EventHandler(replaceWindow_Replace); _findReplaceWindow.ReplaceAll += new EventHandler(replaceWindow_ReplaceAll); // Enable keyboard interop for the findReplaceWindow, otherwise WinForms will intercept all keyboard input. System.Windows.Forms.Integration.ElementHost.EnableModelessKeyboardInterop(_findReplaceWindow); }
public static void DataGridApplyExpressionMenuItem(object sender, DBTableControl.DBEditorTableControl mainTable) { ApplyExpressionWindow getexpwindow = new ApplyExpressionWindow(); getexpwindow.ShowDialog(); if (getexpwindow.DialogResult != null && (bool)getexpwindow.DialogResult) { foreach (DataGridCellInfo cellinfo in mainTable.dbDataGrid.SelectedCells) { // Determine current cells indecies, row and column int columnindex = mainTable.CurrentTable.Columns.IndexOf((string)cellinfo.Column.Header); int rowindex = mainTable.CurrentTable.Rows.IndexOf((cellinfo.Item as DataRowView).Row); // Skip any filtered rows, or any rows with an error in the column we are computing. mainTable.UpdateVisibleRows(); if (mainTable._visibleRows[rowindex] == System.Windows.Visibility.Collapsed || mainTable._errorList.Count(n => n.RowIndex == rowindex && n.ColumnName.Equals((string)cellinfo.Column.Header)) > 0) { continue; } // Get the expression, replacing x for the current cell's value. string expression = getexpwindow.EnteredExpression.Replace("x", string.Format("{0}", mainTable.CurrentTable.Rows[rowindex][columnindex])); // Compute spits out the new value after the current value is applied to the expression given. object newvalue = mainTable.CurrentTable.Compute(expression, ""); // For integer based columns, do a round first if necessary. if (mainTable.EditedFile.CurrentType.Fields[columnindex].TypeCode == TypeCode.Int32 || mainTable.EditedFile.CurrentType.Fields[columnindex].TypeCode == TypeCode.Int16) { int newintvalue; if (!Int32.TryParse(newvalue.ToString(), out newintvalue)) { double tempvalue = Double.Parse(newvalue.ToString()); tempvalue = Math.Round(tempvalue, 0); newintvalue = (int)tempvalue; } newvalue = newintvalue; } mainTable.CurrentTable.Rows[rowindex][columnindex] = newvalue; // Refresh the cell in the UI, using its visual coordinates. mainTable.RefreshCell(mainTable.dbDataGrid.Items.IndexOf(cellinfo.Item), mainTable.dbDataGrid.Columns.IndexOf(cellinfo.Column)); } } }
public static void SelectColumn(object sender, DBTableControl.DBEditorTableControl mainTable) { DataGridColumn col = (((sender as MenuItem).Parent as ContextMenu).PlacementTarget as DataGridColumnHeader).Column; var dbDataGrid = mainTable.dbDataGrid; for (int i = 0; i < dbDataGrid.Items.Count; i++) { // Test if the cell is already contained in SelectedCells DataGridCellInfo cellinfo = new DataGridCellInfo(dbDataGrid.Items[i], col); if (!dbDataGrid.SelectedCells.Contains(cellinfo)) { dbDataGrid.SelectedCells.Add(cellinfo); } } }
public static void ColumnApplyExpression(object sender, DBTableControl.DBEditorTableControl mainTable) { DataGridColumn col = (((sender as MenuItem).Parent as ContextMenu).PlacementTarget as DataGridColumnHeader).Column; string colname = (string)col.Header; ApplyExpressionWindow getexpwindow = new ApplyExpressionWindow(); getexpwindow.ShowDialog(); if (getexpwindow.DialogResult != null && (bool)getexpwindow.DialogResult) { for (int i = 0; i < mainTable.CurrentTable.Rows.Count; i++) { // Skip any filtered rows, or any rows with an error in the column we are computing. mainTable.UpdateVisibleRows(); if (mainTable._visibleRows[i] == System.Windows.Visibility.Collapsed || mainTable._errorList.Count(n => n.RowIndex == i && n.ColumnName.Equals(colname)) > 0) { continue; } // Grab the given expression, modifying it for each cell. string expression = getexpwindow.EnteredExpression.Replace("x", string.Format("{0}", mainTable.CurrentTable.Rows[i][colname])); object newvalue = mainTable.CurrentTable.Compute(expression, ""); int colindex = mainTable.CurrentTable.Columns.IndexOf(colname); // For integer based columns, do a round first if necessary. if (mainTable.EditedFile.CurrentType.Fields[colindex].TypeCode == TypeCode.Int32 || mainTable.EditedFile.CurrentType.Fields[colindex].TypeCode == TypeCode.Int16) { int newintvalue; if (!Int32.TryParse(newvalue.ToString(), out newintvalue)) { double tempvalue = Double.Parse(newvalue.ToString()); tempvalue = Math.Round(tempvalue, 0); newintvalue = (int)tempvalue; } newvalue = newintvalue; } mainTable.CurrentTable.Rows[i][colname] = newvalue; } } mainTable.RefreshColumn(mainTable.dbDataGrid.Columns.IndexOf(col)); }
private static bool ClipboardContainsOnlyRows(DBTableControl.DBEditorTableControl mainTable) { string clipboardText = GetClipboardText(); foreach (string line in clipboardText.Split('\n')) { if (String.IsNullOrEmpty(line)) { continue; } if (!IsLineARow(mainTable, line)) { return(false); } } return(true); }
public static void RenumberMenuItem(object sender, DBTableControl.DBEditorTableControl mainTable) { // Get the column index this context menu was called from. DataGridColumn col = (((sender as MenuItem).Parent as ContextMenu).PlacementTarget as DataGridColumnHeader).Column; string colname = (string)col.Header; List <int> visualroworder = new List <int>(); InputBox renumberInputBox = new InputBox { Text = "Re-Number from", Input = "1" }; if (renumberInputBox.ShowDialog() == System.Windows.Forms.DialogResult.OK) { try { int parsedNumber = int.Parse(renumberInputBox.Input); for (int i = 0; i < mainTable.dbDataGrid.Items.Count; i++) { // Skip any non DataRowView, which should only be the blank row at the bottom. if (!(mainTable.dbDataGrid.Items[i] is DataRowView)) { continue; } // Store the data row index associated with the current visual row to account for column sorting. visualroworder.Add(mainTable.CurrentTable.Rows.IndexOf((mainTable.dbDataGrid.Items[i] as DataRowView).Row)); } // Now that we have a set order, we can assign values. for (int i = 0; i < visualroworder.Count; i++) { mainTable.CurrentTable.Rows[visualroworder[i]][colname] = parsedNumber + i; } } catch (Exception ex) { MessageBox.Show(string.Format("Could not apply values: {0}", ex.Message), "You fail!"); } } mainTable.RefreshColumn(mainTable.dbDataGrid.Columns.IndexOf(col)); }
public static void EditVisibleListMenuItem(object sender, DBTableControl.DBEditorTableControl mainTable) { var hiddencolumnslisteditor = ColumnVisiblityHelper.Show(mainTable); System.Windows.Forms.DialogResult result = hiddencolumnslisteditor.ShowDialog(); if (result == System.Windows.Forms.DialogResult.OK) { mainTable._hiddenColumns.Clear(); mainTable._hiddenColumns = hiddencolumnslisteditor.RightList; foreach (DataColumn column in mainTable.CurrentTable.Columns) { if (hiddencolumnslisteditor.LeftList.Contains(column.ColumnName)) { column.ExtendedProperties["Hidden"] = false; mainTable.dbDataGrid.Columns[column.Ordinal].Visibility = System.Windows.Visibility.Visible; } else { column.ExtendedProperties["Hidden"] = true; if (mainTable.ShowAllColumns) { mainTable.dbDataGrid.Columns[column.Ordinal].Visibility = System.Windows.Visibility.Visible; } else { mainTable.dbDataGrid.Columns[column.Ordinal].Visibility = System.Windows.Visibility.Hidden; } } } mainTable.UpdateConfig(); if (mainTable.ShowAllColumns) { mainTable.Refresh(); } } }
public static void Open(object sender, DBTableControl.DBEditorTableControl mainTable) { ContextMenu currentmenu = (ContextMenu)sender; DataGridColumn col = (currentmenu.PlacementTarget as DataGridColumnHeader).Column; string colname = (string)col.Header; var currentColumn = mainTable.CurrentTable.Columns.IndexOf(colname); var typeCode = mainTable.EditedFile.CurrentType.Fields[currentColumn].TypeCode; Type columntype = DBTableControl.DBEditorTableControl.GetTypeFromCode(typeCode);; foreach (MenuItem item in currentmenu.Items.OfType <MenuItem>()) { // Enable/Disable Remove Sorting item based on if the column is actually sorted or not. if (item.Header.Equals("Remove Sorting")) { item.IsEnabled = col.SortDirection != null; } // Enable/Disable Apply expression and renumber based on column type. if (item.Header.Equals("Apply Expression") || item.Header.Equals("Renumber Cells")) { if (!col.IsReadOnly && (columntype.Name.Equals("Single") || columntype.Name.Equals("Int32") || columntype.Name.Equals("Int16"))) { item.IsEnabled = true; } else { item.IsEnabled = false; } } // Enable.Disable Mass edit, limiting it to string columns only. if (item.Header.Equals("Mass Edit")) { var state = !mainTable.ReadOnly && typeCode == TypeCode.String; item.IsEnabled = state; } } }
public void LoadFilters(DBTableControl.DBEditorTableControl parentDbController) { _parentDbController = parentDbController; filterList.Clear(); _parentDbController._autofilterList.Clear(); string tableName = parentDbController.EditedFile.CurrentType.Name; // If the saved config has not filters, skip. if (!_parentDbController._savedconfig.Filters.ContainsKey(tableName)) { return; } // Load saved filters, attaching activation listeners for each one. foreach (DBFilter filter in _parentDbController._savedconfig.Filters[tableName]) { // Always load filters as inactive. filter.IsActive = false; filter.FilterToggled += new EventHandler(filter_FilterToggled); filterList.Add(filter); } }
private static bool IsLineARow(DBTableControl.DBEditorTableControl mainTable, string line) { if (line.Count(n => n == '\t') >= mainTable.EditedFile.CurrentType.Fields.Count - 1) { bool fullrow = true; string[] cells = line.Split('\t').Take(mainTable.EditedFile.CurrentType.Fields.Count).ToArray(); for (int i = 0; i < cells.Length; i++) { if (String.IsNullOrEmpty(cells[i]) && (mainTable.EditedFile.CurrentType.Fields[i].TypeCode != TypeCode.String) && !mainTable.EditedFile.CurrentType.Fields[i].TypeName.Contains("optstring")) { fullrow = false; break; } } if (fullrow) { return(true); } } return(false); }
public static void ClearTableHiddenMenuItem(DBTableControl.DBEditorTableControl mainTable) { foreach (DataGridColumn column in mainTable.dbDataGrid.Columns) { DataColumn datacolumn = mainTable.CurrentTable.Columns[(string)column.Header]; if (!datacolumn.ExtendedProperties.ContainsKey("Hidden")) { datacolumn.ExtendedProperties.Add("Hidden", false); } datacolumn.ExtendedProperties["Hidden"] = false; column.Visibility = Visibility.Visible; } // Clear the internal hidden columns list. mainTable._hiddenColumns.Clear(); mainTable.UpdateConfig(); if (mainTable.ShowAllColumns) { mainTable.Refresh(); } }
private static bool IsRowValid(DBTableControl.DBEditorTableControl mainTable, string line) { List <string> fields = line.Split('\t').ToList(); List <int> fieldorder = new List <int>(); if (fields.Count < mainTable.CurrentTable.Columns.Count) { PasteError("Error: could not paste following row into table, too few fields.\n\n" + line); return(false); } if (mainTable.MoveAndFreezeKeys) { // Fields may be in altered visual order from data source. fieldorder.AddRange(mainTable.dbDataGrid.Columns.OrderBy(n => n.DisplayIndex).Select(n => mainTable.dbDataGrid.Columns.IndexOf(n))); } else { // Fields are displayed in original data order. for (int i = 0; i < mainTable.CurrentTable.Columns.Count; i++) { fieldorder.Add(i); } } for (int i = 0; i < mainTable.CurrentTable.Columns.Count; i++) { TypeCode fieldtypecode = mainTable.EditedFile.CurrentType.Fields[fieldorder[i]].TypeCode; if (fieldtypecode == TypeCode.String) { continue; } else if (fieldtypecode == TypeCode.Single) { float temp; if (!float.TryParse(fields[i], out temp)) { PasteError(String.Format("Error: could not paste line into table, as '{0}' is not a valid value for '{1}'.\n\n{2}", fields[i], mainTable.CurrentTable.Columns[fieldorder[i]].ColumnName, line)); return(false); } } else if (fieldtypecode == TypeCode.Int32) { int temp; if (!int.TryParse(fields[i], out temp)) { PasteError(String.Format("Error: could not paste line into table, as '{0}' is not a valid value for '{1}'.\n\n{2}", fields[i], mainTable.CurrentTable.Columns[fieldorder[i]].ColumnName, line)); return(false); } } else if (fieldtypecode == TypeCode.Int16) { short temp; if (!short.TryParse(fields[i], out temp)) { PasteError(String.Format("Error: could not paste line into table, as '{0}' is not a valid value for '{1}'.\n\n{2}", fields[i], mainTable.CurrentTable.Columns[fieldorder[i]].ColumnName, line)); return(false); } } } return(true); }
public static void OnCanExecutePaste(DBTableControl.DBEditorTableControl mainTable, CanExecuteRoutedEventArgs args) { args.CanExecute = mainTable.dbDataGrid.CurrentCell != null; args.CanExecute = !mainTable.ReadOnly; args.Handled = true; }
public static void OnExecutedPaste(DBTableControl.DBEditorTableControl mainTable) { string clipboarddata = GetClipboardText(); int rowindex; int datarowindex; int columnindex; int datacolumnindex; if (ClipboardIsEmpty()) { // Clipboard Empty } else if (ClipboardContainsSingleCell()) { // Single Cell Paste string pastevalue = clipboarddata.Trim(); foreach (DataGridCellInfo cellinfo in mainTable.dbDataGrid.SelectedCells) { // Get both visible and data row index rowindex = mainTable.dbDataGrid.Items.IndexOf(cellinfo.Item); datarowindex = mainTable.CurrentTable.Rows.IndexOf((cellinfo.Item as DataRowView).Row); // Additional error checking for the visibleRows internal list. if (datarowindex >= mainTable._visibleRows.Count) { mainTable.UpdateVisibleRows(); } // Selecting cells while the table is filtered will select collapsed rows, so skip them here. if (mainTable._visibleRows[datarowindex] == System.Windows.Visibility.Collapsed) { continue; } // Get both visible and data column index columnindex = mainTable.dbDataGrid.Columns.IndexOf(cellinfo.Column); datacolumnindex = mainTable.CurrentTable.Columns.IndexOf((string)cellinfo.Column.Header); mainTable.CurrentTable.Rows[datarowindex].BeginEdit(); if (!TryPasteValue(mainTable.CurrentTable, datarowindex, datacolumnindex, pastevalue)) { // Paste Error } mainTable.CurrentTable.Rows[datarowindex].EndEdit(); mainTable.RefreshCell(rowindex, columnindex); } } else if (!ClipboardContainsOnlyRows(mainTable)) { if (mainTable.dbDataGrid.SelectedItems.OfType <DataRowView>().Count() != mainTable.dbDataGrid.SelectedItems.Count) { // The blank row is selected, abort. MessageBox.Show("Only select the blank row when pasting rows.", "Selection Error", MessageBoxButton.OK, MessageBoxImage.Warning); return; } // Use -1 values to indicate that nothing is selected, and to paste any full rows the // clipboard might contain as new rows. int basecolumnindex = -1; rowindex = -1; if (mainTable.dbDataGrid.SelectedCells.Count > 1) { // User has more than 1 cells selected, therefore the selection must match the clipboard data. if (!PasteMatchesSelection(mainTable, clipboarddata)) { // Warn user if (MessageBox.Show("Warning! Cell selection does not match copied data, attempt to paste anyway?", "Selection Error", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.No) { return; } } // Set values to the first cell's coordinates // Get both visible and data row index rowindex = mainTable.dbDataGrid.Items.IndexOf(mainTable.dbDataGrid.SelectedCells[0].Item); basecolumnindex = mainTable.dbDataGrid.SelectedCells[0].Column.DisplayIndex; // Determine upper left corner of selection foreach (DataGridCellInfo cellinfo in mainTable.dbDataGrid.SelectedCells) { rowindex = Math.Min(rowindex, mainTable.dbDataGrid.Items.IndexOf(cellinfo.Item)); basecolumnindex = Math.Min(basecolumnindex, cellinfo.Column.DisplayIndex); } } else if (mainTable.dbDataGrid.SelectedCells.Count == 1) { // User has 1 cell selected, assume it is the top left corner and attempt to paste. rowindex = mainTable.dbDataGrid.Items.IndexOf(mainTable.dbDataGrid.SelectedCells[0].Item); basecolumnindex = mainTable.dbDataGrid.SelectedCells[0].Column.DisplayIndex; } List <string> pasteinstructions = new List <string>(); foreach (string line in clipboarddata.Split('\n')) { columnindex = basecolumnindex; if (rowindex > mainTable.CurrentTable.Rows.Count - 1 || columnindex == -1) { if (IsLineARow(mainTable, line)) { // We have a full row, but no where to paste it, so add it as a new row. DataRow newrow = mainTable.CurrentTable.NewRow(); if (mainTable.MoveAndFreezeKeys) { // Data is being displayed with keys moved, so assume the clipboard data matches the visual appearance and not // the order of the data source. object tempitem; List <object> itemarray = line.Split('\t').Take(mainTable.EditedFile.CurrentType.Fields.Count).ToList <object>(); for (int i = mainTable.CurrentTable.PrimaryKey.Count() - 1; i >= 0; i--) { tempitem = itemarray[i]; itemarray.RemoveAt(i); itemarray.Insert(mainTable.CurrentTable.Columns.IndexOf(mainTable.CurrentTable.PrimaryKey[i]), tempitem); } // Once we have reordered the clipboard data to match the data source, convert to an object[] newrow.ItemArray = itemarray.ToArray(); } else { // Data is displayed as it is stored, so assume the clipboard data is ordered the same way. newrow.ItemArray = line.Split('\t').Take(mainTable.EditedFile.CurrentType.Fields.Count).ToArray <object>(); } mainTable.CurrentTable.Rows.Add(newrow); } rowindex++; continue; } if (String.IsNullOrEmpty(line.Trim())) { rowindex++; continue; } // Convert visual row and column index to data row and column index. datarowindex = mainTable.CurrentTable.Rows.IndexOf((mainTable.dbDataGrid.Items[rowindex] as DataRowView).Row); // Additional error checking for the visibleRows internal list. if (datarowindex >= mainTable._visibleRows.Count) { mainTable.UpdateVisibleRows(); } // Skip past any collapsed (filtered) rows. while (mainTable._visibleRows[datarowindex] == System.Windows.Visibility.Collapsed) { rowindex++; datarowindex = mainTable.CurrentTable.Rows.IndexOf((mainTable.dbDataGrid.Items[rowindex] as DataRowView).Row); if (rowindex >= mainTable.CurrentTable.Rows.Count) { break; } } foreach (string cell in line.Replace("\r", "").Split('\t')) { if (columnindex > mainTable.CurrentTable.Columns.Count - 1) { break; } if (String.IsNullOrEmpty(cell.Trim())) { columnindex++; continue; } // Convert visual column index, the display index not its location in the datagrid's collection, to data column index. datacolumnindex = mainTable.CurrentTable.Columns.IndexOf((string)mainTable.dbDataGrid.Columns.Single(n => n.DisplayIndex == columnindex).Header); // Since refresh works on the visual tree, and the visual tree is not affected by DisplayIndex, find the columns location // in the datagrid's column collection to pass on. int refreshcolumnindex = mainTable.dbDataGrid.Columns.IndexOf(mainTable.dbDataGrid.Columns.Single(n => n.DisplayIndex == columnindex)); // Rather than attempting to modify cells as we go, we should modify them in batches // since any kind of sorting may interfere with paste order in real time. pasteinstructions.Add(String.Format("{0};{1};{2};{3};{4}", datarowindex, rowindex, datacolumnindex, refreshcolumnindex, cell)); columnindex++; } rowindex++; } // Now that we have a list of paste instructions, execute them simultaneously across the data source // to avoid interference from any visual resorting. // Instruction Format: Data Row index;Visual Row index;Data Column index;Visual Column index;value foreach (string instruction in pasteinstructions) { // Parse out the instructions. string[] parameters = instruction.Split(';'); datarowindex = int.Parse(parameters[0]); rowindex = int.Parse(parameters[1]); datacolumnindex = int.Parse(parameters[2]); columnindex = int.Parse(parameters[3]); // Edit currentTable mainTable.CurrentTable.Rows[datarowindex].BeginEdit(); mainTable.CurrentTable.Rows[datarowindex][datacolumnindex] = parameters[4]; mainTable.CurrentTable.Rows[datarowindex].EndEdit(); // Refresh the visual cell mainTable.RefreshCell(rowindex, columnindex); } } else { // Paste Rows, with no floater cells. if (mainTable.dbDataGrid.SelectedCells.Count == (mainTable.dbDataGrid.SelectedItems.Count * mainTable.EditedFile.CurrentType.Fields.Count)) { // Only rows are selected. // Since the SelectedItems list is in the order of selection and NOT in the order of appearance we need // to create a custom sorted list of indicies to paste to. List <int> indiciesToPaste = new List <int>(); List <int> dataindiciesToPaste = new List <int>(); int testindex; foreach (DataRowView rowview in mainTable.dbDataGrid.SelectedItems.OfType <DataRowView>()) { testindex = mainTable.CurrentTable.Rows.IndexOf(rowview.Row); // Additional error checking for the visibleRows internal list. if (testindex >= mainTable._visibleRows.Count) { mainTable.UpdateVisibleRows(); } // Skip any collapsed (filtered) rows. if (mainTable._visibleRows[testindex] == System.Windows.Visibility.Visible) { indiciesToPaste.Add(mainTable.dbDataGrid.Items.IndexOf(rowview)); } } indiciesToPaste.Sort(); // Now that we have the selected rows visual locations, we need to determine their locations in our data source. foreach (int i in indiciesToPaste) { dataindiciesToPaste.Add(mainTable.CurrentTable.Rows.IndexOf((mainTable.dbDataGrid.Items[i] as DataRowView).Row)); } // We now have a list of data indicies sorted in visual order. int currentindex = 0; foreach (string line in clipboarddata.Replace("\r", "").Split('\n')) { if (!IsLineARow(mainTable, line) || String.IsNullOrEmpty(line) || !IsRowValid(mainTable, line)) { currentindex++; continue; } if (currentindex >= dataindiciesToPaste.Count) { // Add new row DataRow newrow = mainTable.CurrentTable.NewRow(); if (mainTable.MoveAndFreezeKeys) { // Data is being displayed with keys moved, so assume the clipboard data matches the visual appearance and not // the order of the data source. object tempitem; List <object> itemarray = line.Split('\t').Take(mainTable.EditedFile.CurrentType.Fields.Count).ToList <object>(); for (int i = mainTable.CurrentTable.PrimaryKey.Count() - 1; i >= 0; i--) { tempitem = itemarray[i]; itemarray.RemoveAt(i); itemarray.Insert(mainTable.CurrentTable.Columns.IndexOf(mainTable.CurrentTable.PrimaryKey[i]), tempitem); } // Once we have reordered the clipboard data to match the data source, convert to an object[] newrow.ItemArray = itemarray.ToArray(); } else { // Data is displayed as it is stored, so assume the clipboard data is ordered the same way. newrow.ItemArray = line.Split('\t').Take(mainTable.EditedFile.CurrentType.Fields.Count).ToArray <object>(); } mainTable.CurrentTable.Rows.Add(newrow); currentindex++; continue; } mainTable.CurrentTable.Rows[dataindiciesToPaste[currentindex]].BeginEdit(); if (mainTable.MoveAndFreezeKeys) { // Data is being displayed with keys moved, so assume the clipboard data matches the visual appearance and not // the order of the data source. object tempitem; List <object> itemarray = line.Split('\t').Take(mainTable.EditedFile.CurrentType.Fields.Count).ToList <object>(); for (int i = mainTable.CurrentTable.PrimaryKey.Count() - 1; i >= 0; i--) { tempitem = itemarray[i]; itemarray.RemoveAt(i); itemarray.Insert(mainTable.CurrentTable.Columns.IndexOf(mainTable.CurrentTable.PrimaryKey[i]), tempitem); } // Once we have reordered the clipboard data to match the data source, convert to an object[] mainTable.CurrentTable.Rows[dataindiciesToPaste[currentindex]].ItemArray = itemarray.ToArray(); } else { // Data is displayed as it is stored, so assume the clipboard data is ordered the same way. mainTable.CurrentTable.Rows[dataindiciesToPaste[currentindex]].ItemArray = line.Split('\t').Take(mainTable.EditedFile.CurrentType.Fields.Count).ToArray <object>(); } mainTable.CurrentTable.Rows[dataindiciesToPaste[currentindex]].EndEdit(); currentindex++; } mainTable.Refresh(true); } else { // Please select rows. MessageBox.Show("When pasting rows, please use the row header button to select entire rows only.", "Selection Error", MessageBoxButton.OK, MessageBoxImage.Warning); } } }
private static bool FilterTestRow(int rowindex, DBTableControl.DBEditorTableControl mainTable, IList <DBFilter> filterList, FilterSettings filterSettings) { int colindex; // Test row against active advanced filters. foreach (DBFilter filter in filterList) { if (!filter.IsActive) { continue; } colindex = mainTable.CurrentTable.Columns.IndexOf(filter.ApplyToColumn); if (!FilterTestValue(mainTable.CurrentTable.Rows[rowindex][colindex], filter.FilterValue, filter.MatchMode)) { return(false); } } // Test row against currently active column autofilters. foreach (DBFilter filter in mainTable._autofilterList) { if (!filter.IsActive) { continue; } colindex = mainTable.CurrentTable.Columns.IndexOf(filter.ApplyToColumn); if (!FilterTestValue(mainTable.CurrentTable.Rows[rowindex][colindex], filter.FilterValue, filter.MatchMode)) { return(false); } } // If either the error or warning filter is engaged test the row agains them as well. if (filterSettings.ErrorDockPanelVisible) { // If both filters are engaged either or will pass. if (filterSettings.ErrorFilter && filterSettings.WarningFilter) { if (mainTable._errorList.Count(n => n.RowIndex == rowindex && n.ErrorMessage.Contains("Error:")) == 0 && mainTable._errorList.Count(n => n.RowIndex == rowindex && n.ErrorMessage.Contains("Warning:")) == 0) { return(false); } }// If only the Warnings filter is engaged, only warnings pass. else if (!filterSettings.ErrorFilter && filterSettings.WarningFilter) { if (mainTable._errorList.Count(n => n.RowIndex == rowindex && n.ErrorMessage.Contains("Warning:")) == 0) { return(false); } }// If only the Errors filter is engaged, only errors pass. else if (filterSettings.ErrorFilter && !filterSettings.WarningFilter) { if (mainTable._errorList.Count(n => n.RowIndex == rowindex && n.ErrorMessage.Contains("Error:")) == 0) { return(false); } } } return(true); }
public static void DataGridContextMenu(object sender, DBTableControl.DBEditorTableControl mainTable) { bool cellsselected = false; if (mainTable.dbDataGrid.SelectedCells.Count > 0) { cellsselected = true; } ContextMenu menu = (ContextMenu)sender; foreach (MenuItem item in menu.Items.OfType <MenuItem>()) { if (item.Header.Equals("Copy")) { item.IsEnabled = cellsselected; } else if (item.Header.Equals("Paste")) { if (mainTable.ReadOnly) { item.IsEnabled = false; } else { item.IsEnabled = cellsselected; } } else if (item.Header.Equals("Apply Expression to Selected Cells")) { item.IsEnabled = cellsselected; if (cellsselected) { Type columntype; foreach (DataGridCellInfo cellinfo in mainTable.dbDataGrid.SelectedCells) { columntype = DBTableControl.DBEditorTableControl.GetTypeFromCode(mainTable.EditedFile.CurrentType.Fields[mainTable.CurrentTable.Columns.IndexOf((string)cellinfo.Column.Header)].TypeCode); if (mainTable.ReadOnly || !(columntype.Name.Equals("Single") || columntype.Name.Equals("Int32") || columntype.Name.Equals("Int16"))) { item.IsEnabled = false; break; } } } } else if (item.Header.Equals("Mass Edit String Cells")) { item.IsEnabled = cellsselected; if (cellsselected) { foreach (int colindex in mainTable.dbDataGrid.SelectedCells.Select(n => mainTable.CurrentTable.Columns[(string)n.Column.Header].Ordinal).Distinct()) { if (mainTable.EditedFile.CurrentType.Fields[colindex].TypeCode != TypeCode.String) { item.IsEnabled = false; break; } } } } else if (item.Header.Equals("Revert Cell to Original Value")) { if (mainTable.ReadOnly) { item.IsEnabled = false; } else { item.IsEnabled = cellsselected; } } } }