private void _SearchText(string text, DataGrid dg) { if (dg == null) { return; } ICollectionView cv = CollectionViewSource.GetDefaultView(dg.ItemsSource); if (cv == null) { return; } if (string.IsNullOrWhiteSpace(text)) { // when text is empty or button clicked, clear search results!! if (cv.Filter != null) { dg.CancelEdit(DataGridEditingUnit.Row); cv.Filter = null; dg.InvalidateVisual(); } return; } dg.CancelEdit(DataGridEditingUnit.Row); cv.Filter = _BuildTextFilter(text.ToLowerInvariant()); dg.InvalidateVisual(); }
public static void EditDataGrid <T>(DataGridCellEditEndingEventArgs e, string table_name, DataGrid dataGrid) // Editing DataGrid Row { dynamic selected_items = (T)dataGrid.SelectedItem; // Getting DataGrid selected items(can get Student class properties) string column_name = e.Column.SortMemberPath; // Getting edited/changed column name string new_value = ((TextBox)e.EditingElement).Text.Trim(); // Getting entered value Type propertyInfo = typeof(T); string old_value = propertyInfo.GetProperty(column_name).GetValue(selected_items, null).ToString(); // Get previous value in edited cells if (e.EditAction == DataGridEditAction.Commit && !new_value.Equals("") && !new_value.Equals(old_value)) // Checking entered value for empty { MessageBoxResult msgBox = MessageBox.Show("Вы действительно хотите изменить текушие данные?", "Изменение данных", MessageBoxButton.YesNo); if (msgBox == MessageBoxResult.Yes) // If answer YES { SQLiteAdapter.ChangeValueById(table_name, selected_items.id, column_name + " = '" + new_value + "'"); // TODO: Добавить проверку выполненности изменения данных в БД, если FALSE, то откат изменений в DataGrid } else { // If answer No dataGrid.CancelEdit(); //DataGridEditingUnit.Row } } else if (e.EditAction == DataGridEditAction.Cancel) { return; } else { dataGrid.CancelEdit(); } // Cancel editing row }
private void stopEdit(DataGrid grid) { try{ grid.CommitEdit(DataGridEditingUnit.Row, true); } catch { grid.CancelEdit(); grid.CancelEdit(DataGridEditingUnit.Row); } }
/// <summary> /// Se ejecuta cuando la fila pierde el foco, o termina la edicion (Commit o Cancel) /// </summary> /// <history> /// [edgrodriguez] 11/08/2016 Created. /// </history> private void dtgGifts_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e) { DataGrid dtg = sender as DataGrid; InvitationGift invitationGift = e.Row.Item as InvitationGift; if (e.EditAction == DataGridEditAction.Commit) { if (_isCellCancel) { dtg.RowEditEnding -= dtgGifts_RowEditEnding; dtg.CancelEdit(); dtg.RowEditEnding -= dtgGifts_RowEditEnding; } else { if (invitationGift.igQty != 0 && !string.IsNullOrEmpty(invitationGift.iggi)) { return; } UIHelper.ShowMessage("Please enter the required fields Qty and Gift to continue", MessageBoxImage.Exclamation, "Intelligence Marketing"); e.Cancel = true; } } }
private void ApplyFilters() { #region bindinglistcollectionview concatenating and applying filter string newFilter = ""; foreach (KeyValuePair <string, string> KVP in Filters) { if (KVP.Value.Trim(new char[] { ' ' }) != "") { if (newFilter.Length > 0) { newFilter += " AND " + KVP.Value; } else { newFilter += KVP.Value; } } } DG.CancelEdit(DataGridEditingUnit.Row); Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate() { StatusString = "Применяю фильтры"; loadingIcon.RotateMe(); BLCV.CustomFilter = newFilter; //StatusString = ""; loadingIcon.StopRotation(); })); #endregion }
private void CancelChanges_Click(object sender, RoutedEventArgs e) { if (dataGrid != null) { dataGrid.CancelEdit(); dataGrid = null; } }
protected virtual void RollbackEditingItemAfterEdit() { _service.AddPhrase(SelectedPack.Id, BackupItem); var index = SelectedPack.Phrases.IndexOf(SelectedItem); SelectedPack.Phrases[index] = BackupItem; DataGrid.CancelEdit(); }
void DataGrid_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) { if (e.ColumnIndex == CurveName.Index) { if (CurveNames.Any(name => name == (string)e.FormattedValue)) { DataGrid.CancelEdit(); } } }
/// <summary> /// No permite que se agreguen filas vacias /// </summary> /// <history> /// [emoguel] created 25/05/2016 /// </history> private void dgr_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e) { if (e.EditAction == DataGridEditAction.Commit && isCellCancel) { DataGrid dgr = (DataGrid)sender; dgr.RowEditEnding -= dgr_RowEditEnding; dgr.CancelEdit(); dgr.RowEditEnding += dgr_RowEditEnding; } }
private static void OnClick(object sender, RoutedEventArgs e) { if (sender is Button) { DataGrid dataGrid = FindParent <DataGrid>((Button)sender); if (dataGrid != null) { dataGrid.CancelEdit(); } } }
private void RefreshEngines() { if (mainDataGrid != null) { mainDataGrid.CommitEdit(); mainDataGrid.CancelEdit(); ICollectionView view = CollectionViewSource.GetDefaultView(mainDataGrid.ItemsSource); if (view != null) { view.SortDescriptions.Clear(); foreach (DataGridColumn column in mainDataGrid.Columns) { column.SortDirection = null; } } mainDataGrid.Items.Refresh(); } else { throw new NullReferenceException("mainDataGrid is null"); } }
private void CollectionView_CurrentChanging(object sender, DataGridCurrentChangingEventArgs e) { if (_owner.NoCurrentCellChangeCount == 0 && !_expectingCurrentChanged && !CommittingEdit && !_owner.CommitEdit()) { // If CommitEdit failed, then the user has most likely input invalid data. // We should cancel the current change if we can, otherwise we have to abort the edit. if (e.IsCancelable) { e.Cancel = true; } else { _owner.CancelEdit(DataGridEditingUnit.Row, false); } } }
/// <summary> /// To DataGrid.CellEditEnding event, the edition is committed. /// </summary> public static void CellEditEnding(object sender, DataGridCellEditEndingEventArgs e) { try { var datagrid = sender as DataGrid; if (datagrid == null) { return; } if (!GetIsManualeditCommit(datagrid)) { SetIsManualeditCommit(datagrid, true); DataGrid grid = (DataGrid)sender; grid.CommitEdit(DataGridEditingUnit.Row, true); grid.CancelEdit(); //Cancel modification if it is not valided. SetIsManualeditCommit(datagrid, false); } } catch (Exception ex) { } }
private void DeleteCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) { try { DataGrid exexustiondetail = (DataGrid)e.Source; MessageBoxResult result = MessageBox.Show("Are you sure want to Delete?", "Delete", MessageBoxButton.YesNo, MessageBoxImage.Question); if (result == MessageBoxResult.Yes) { production_execution production_execution = production_executionViewSource.View.CurrentItem as production_execution; //DeleteDetailGridRow exexustiondetail.CancelEdit(); production_execution_detail production_execution_detail = e.Parameter as production_execution_detail; production_execution_detail.State = EntityState.Deleted; RefreshData(); } } catch (Exception ex) { toolBar.msgError(ex); } }
private void TextBoxSearch_TextChanged(object sender, TextChangedEventArgs e) { var tb = sender as TextBox; if (string.IsNullOrWhiteSpace(tb.Text) == false) { return; } DataGrid dg = null; if (sender == TbMappingProjConfSearch) { dg = DgMappingProjConf; } else if (sender == TbMappingGlossariesToolSearch) { dg = DgMappingGlossaries; } else if (sender == TbMappingAllSearch) { dg = DgMappingAll; } if (dg == null || dg.ItemsSource == null) { return; } ICollectionView cv = CollectionViewSource.GetDefaultView(dg.ItemsSource); if (cv != null && cv.Filter != null) { dg.CancelEdit(DataGridEditingUnit.Row); cv.Filter = null; } }
/// <summary> /// No permite agregar filas vacias /// </summary> /// <history> /// [emoguel] created 06/06/2016 /// </history> private void dgr_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e) { if (e.EditAction == DataGridEditAction.Commit) { DataGrid dgr = sender as DataGrid; if (_isCellCancel) { dgr.RowEditEnding -= dgr_RowEditEnding; dgr.CancelEdit(); dgr.RowEditEnding += dgr_RowEditEnding; } else { switch (dgr.Name) { case "dgrCountries": { cmbCountries.Header = "Country (" + (dgr.Items.Count - 1) + ")"; break; } case "dgrAgencies": { cmbAgencies.Header = "Agency (" + (dgr.Items.Count - 1) + ")"; break; } case "dgrContracts": { cmbContracts.Header = "Contract (" + (dgr.Items.Count - 1) + ")"; break; } } } } }
/// <summary> /// Guarda o modifica los horarios de tour despues de editar el datagrid /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// <history> /// [vku] 27/Jun/2016 Created /// </history> private async void dgrTourTimes_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e) { DataGrid dgr = sender as DataGrid; dgr.RowEditEnding -= dgrTourTimes_RowEditEnding; if (isCancel) { dgr.CancelEdit(); dgr.RowEditEnding += dgrTourTimes_RowEditEnding; } else { int nRes = 0; switch (_enumTourTimes) { #region TourTime case EnumTourTimesSchema.ttsByLeadSourceSalesRoom: TourTime ttbylssr = e.Row.DataContext as TourTime; if (isInsert) { if (Validate(ttbylssr)) { if (UIHelper.ShowMessage("Are you sure you want add new Tour Time?", MessageBoxImage.Question) == MessageBoxResult.Yes) { dgr.CommitEdit(); status.Visibility = Visibility.Visible; txtStatus.Text = "Saving Data..."; ttbylssr.ttls = cboLeadSource.SelectedValue.ToString(); ttbylssr.ttsr = cboSalesRoom.SelectedValue.ToString(); nRes = await BREntities.OperationEntity(ttbylssr, EnumMode.Add); dgr.Items.Refresh(); dgr.RowEditEnding += dgrTourTimes_RowEditEnding; } else { dgr.CancelEdit(); dgr.RowEditEnding += dgrTourTimes_RowEditEnding; } } else { e.Cancel = true; dgr.RowEditEnding += dgrTourTimes_RowEditEnding; } } else { status.Visibility = Visibility.Visible; txtStatus.Text = "Saving Data..."; nRes = await BREntities.OperationEntity(ttbylssr, EnumMode.Edit); dgr.RowEditEnding += dgrTourTimes_RowEditEnding; } break; #endregion #region TourTimesByDay case EnumTourTimesSchema.ttsByLeadSourceSalesRoomWeekDay: TourTimeByDay ttbylssrwd = e.Row.DataContext as TourTimeByDay; if (isInsert) { if (Validate(ttbylssrwd)) { if (UIHelper.ShowMessage("Are you sure you want add new Tour Time?", MessageBoxImage.Question) == MessageBoxResult.Yes) { dgr.CommitEdit(); status.Visibility = Visibility.Visible; txtStatus.Text = "Saving Data..."; ttbylssrwd.ttls = cboLeadSource.SelectedValue.ToString(); ttbylssrwd.ttsr = cboSalesRoom.SelectedValue.ToString(); ttbylssrwd.ttDay = Convert.ToByte(cboWeekDay.SelectedValue.ToString()); nRes = await BREntities.OperationEntity(ttbylssrwd, EnumMode.Add); dgr.Items.Refresh(); dgr.RowEditEnding += dgrTourTimes_RowEditEnding; } else { dgr.CancelEdit(); dgr.RowEditEnding += dgrTourTimes_RowEditEnding; } } else { e.Cancel = true; dgr.RowEditEnding += dgrTourTimes_RowEditEnding; } } else { status.Visibility = Visibility.Visible; txtStatus.Text = "Saving Data..."; nRes = await BREntities.OperationEntity(ttbylssrwd, EnumMode.Edit); dgr.RowEditEnding += dgrTourTimes_RowEditEnding; } break; #endregion #region TourTimeBySalesRoomWeekDay case EnumTourTimesSchema.ttsBySalesRoomWeekDay: TourTimeBySalesRoomWeekDay ttbysrwd = e.Row.DataContext as TourTimeBySalesRoomWeekDay; if (isInsert) { if (Validate(ttbysrwd)) { if (UIHelper.ShowMessage("Are you sure you want add new Tour Time?", MessageBoxImage.Question) == MessageBoxResult.Yes) { dgr.CommitEdit(); status.Visibility = Visibility.Visible; txtStatus.Text = "Saving Data..."; ttbysrwd.ttsr = cboSalesRoom.SelectedValue.ToString(); ttbysrwd.ttDay = Convert.ToByte(cboWeekDay.SelectedValue.ToString()); nRes = await BREntities.OperationEntity(ttbysrwd, EnumMode.Add); dgr.Items.Refresh(); dgr.RowEditEnding += dgrTourTimes_RowEditEnding; } else { dgr.CancelEdit(); dgr.RowEditEnding += dgrTourTimes_RowEditEnding; } } else { e.Cancel = true; dgr.RowEditEnding += dgrTourTimes_RowEditEnding; } } else { status.Visibility = Visibility.Visible; txtStatus.Text = "Saving Data..."; nRes = await BREntities.OperationEntity(ttbysrwd, EnumMode.Edit); dgr.RowEditEnding += dgrTourTimes_RowEditEnding; } break; #endregion } status.Visibility = Visibility.Collapsed; StatusBarReg.Content = dgrTourTimes.Items.Count - 1 + " Tour Times."; } }
private void RectangleSelection_PointerMoved(object sender, PointerRoutedEventArgs e) { if (scrollBar == null) { return; } var currentPoint = e.GetCurrentPoint(uiElement); var verticalOffset = scrollBar.Value - uiElement.ColumnHeaderHeight; if (selectionState == SelectionState.Starting) { if (!HasMovedMinimalDelta(originDragPoint.X, originDragPoint.Y - verticalOffset, currentPoint.Position.X, currentPoint.Position.Y)) { return; } if (uiElement.CurrentColumn != null) { uiElement.CancelEdit(); } selectionStrategy.StartSelection(); OnSelectionStarted(); selectionState = SelectionState.Active; } if (currentPoint.Properties.IsLeftButtonPressed) { var originDragPointShifted = new Point(originDragPoint.X, originDragPoint.Y - verticalOffset); // Initial drag point relative to the topleft corner base.DrawRectangle(currentPoint, originDragPointShifted, uiElement); // Selected area considering scrolled offset var rect = new System.Drawing.Rectangle((int)Canvas.GetLeft(selectionRectangle), (int)Math.Min(originDragPoint.Y, currentPoint.Position.Y + verticalOffset), (int)selectionRectangle.Width, (int)Math.Abs(originDragPoint.Y - (currentPoint.Position.Y + verticalOffset))); var dataGridRowsPosition = new Dictionary <DataGridRow, System.Drawing.Rectangle>(); double actualWidth = -1; foreach (var row in dataGridRows) { if (row.Visibility != Visibility.Visible) { continue; // Skip invalid/invisible rows } if (actualWidth < 0) { var temp = new List <DataGridCell>(); DependencyObjectHelpers.FindChildren <DataGridCell>(temp, row); // Find cells inside row actualWidth = temp.Sum(x => x.ActualWidth); // row.ActualWidth reports incorrect width } var gt = row.TransformToVisual(uiElement); var itemStartPoint = gt.TransformPoint(new Point(0, verticalOffset)); // Get item position relative to the top of the list (considering scrolled offset) var itemRect = new System.Drawing.Rectangle((int)itemStartPoint.X, (int)itemStartPoint.Y, (int)actualWidth, (int)row.ActualHeight); itemsPosition[row.DataContext] = itemRect; // Update item position dataGridRowsPosition[row] = itemRect; // Update ui row position } foreach (var item in itemsPosition.ToList()) { try { if (rect.IntersectsWith(item.Value)) { selectionStrategy.HandleIntersectionWithItem(item.Key); } else { selectionStrategy.HandleNoIntersectionWithItem(item.Key); } } catch (ArgumentException) { // Item is not present in the ItemsSource itemsPosition.Remove(item); } } if (currentPoint.Position.Y > uiElement.ActualHeight - 20) { // Scroll down the list if pointer is at the bottom // Check if there is a loaded row outside the viewport var item = dataGridRowsPosition.OrderBy(x => x.Value.Y).SkipWhile(x => x.Value.Y <= verticalOffset + uiElement.ActualHeight).Select(x => x.Key).FirstOrDefault(); if (item == null) { if (dataGridRowsPosition.Any()) { // Last loaded item is fully visible, ge thet next one from bound item source var index = dataGridRowsPosition.OrderBy(x => x.Value.Y).Last().Key.GetIndex(); var source = (System.Collections.IList)uiElement.ItemsSource; uiElement.ScrollIntoView(source[Math.Min(Math.Max(index + 1, 0), source.Count - 1)], null); } } else { uiElement.ScrollIntoView(item.DataContext, null); } } else if (currentPoint.Position.Y < 20) { // Scroll up the list if pointer is at the top // Check if there is a loaded row outside the viewport var item = dataGridRowsPosition.OrderBy(x => x.Value.Y).TakeWhile(x => x.Value.Y + x.Value.Height <= scrollBar.Value).Select(x => x.Key).LastOrDefault(); if (item == null) { if (dataGridRowsPosition.Any()) { // First loaded item is fully visible, ge thet previous one from bound item source var index = dataGridRowsPosition.OrderBy(x => x.Value.Y).First().Key.GetIndex(); var source = (System.Collections.IList)uiElement.ItemsSource; uiElement.ScrollIntoView(source[Math.Min(Math.Max(index - 1, 0), source.Count - 1)], null); } } else { uiElement.ScrollIntoView(item.DataContext, null); } } } }
public virtual void EditFirstCell(DataGridEditAction cellEditAction, DataGridEditAction?rowEditAction, DataGridDelegate subscribeToEvent, DataGridCellValidateDelegate validateEvent, DataGridDelegate unsubscribeToEvent) { // The first customer property should always be a string if (properties[0].PropertyType == typeof(string)) { DataGrid dataGrid = new DataGrid(); string originalValue; string updatedValue; dataGrid.ItemsSource = null; dataGrid.SelectedItems.Clear(); rowLoaded = false; dataGridRow = null; isLoaded = false; dataGrid.Loaded += new RoutedEventHandler(dataGrid_Loaded); dataGrid.ColumnWidth = new DataGridLength(50); dataGrid.Width = 650; dataGrid.Height = 250; CustomerList customerList = new CustomerList(1); customerList[0].LastName = "A"; PagedCollectionView pagedCollectionView = new PagedCollectionView(customerList); pagedCollectionView.SortDescriptions.Add(new System.ComponentModel.SortDescription("LastName", System.ComponentModel.ListSortDirection.Ascending)); TestPanel.Children.Add(dataGrid); EnqueueConditional(delegate { return(isLoaded); }); this.EnqueueYieldThread(); EnqueueCallback(delegate { dataGrid.LoadingRow += new EventHandler <DataGridRowEventArgs>(dataGrid_LoadingRowGetRow); subscribeToEvent(dataGrid); dataGrid.ItemsSource = pagedCollectionView; }); EnqueueConditional(delegate { return(rowLoaded); }); this.EnqueueYieldThread(); EnqueueCallback(delegate { dataGrid.LoadingRow -= new EventHandler <DataGridRowEventArgs>(dataGrid_LoadingRowGetRow); bool success = dataGrid.BeginEdit(); Assert.IsTrue(success, "BeginEdit was not successful"); }); this.EnqueueYieldThread(); //} EnqueueCallback(delegate { //Set column to valid value Assert.IsTrue(dataGrid.Columns[0].GetCellContent(customerList[0]) is TextBox, "Not a TextBox"); TextBox cell = ((TextBox)dataGrid.CurrentColumn.GetCellContent(customerList[0])); originalValue = cell.Text; ((TextBox)dataGrid.CurrentColumn.GetCellContent(customerList[0])).Text = Common.RandomString(10); updatedValue = cell.Text; // Either commit or cancel the cell edit if (cellEditAction == DataGridEditAction.Commit) { dataGrid.CommitEdit(DataGridEditingUnit.Cell, true /*exitEditing*/); } else { dataGrid.CancelEdit(DataGridEditingUnit.Cell); } // Either commit or cancel the row edit if (rowEditAction == DataGridEditAction.Commit) { dataGrid.CommitEdit(DataGridEditingUnit.Row, true /*exitEditing*/); } else if (rowEditAction == DataGridEditAction.Cancel) { dataGrid.CancelEdit(DataGridEditingUnit.Row); } updatedValue = properties[0].GetValue(customerList[0], null) as String; validateEvent(dataGrid, originalValue, updatedValue); unsubscribeToEvent(dataGrid); }); } }
private void CancelClick(object sender, RoutedEventArgs e) { DataGrid.CancelEdit(); DialogResult = false; }
/// <summary> /// Cancela o finalizá la edicion de un registro /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// <history> /// [emoguel] created 09/07/2016 /// </history> private void dgr_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e) { DataGrid dgr = sender as DataGrid; if (e.EditAction == DataGridEditAction.Commit) { if (dgr.CurrentColumn != null) { switch (dgr.CurrentColumn.SortMemberPath) { case "gpQty": { GiftPackageItem giftInPack = (GiftPackageItem)e.Row.Item; if (giftInPack.gpQty < 1) { e.Cancel = true; UIHelper.ShowMessage("Quantity can no be lower than 1."); } else if (string.IsNullOrWhiteSpace(giftInPack.gpgi)) { e.Cancel = true; UIHelper.ShowMessage("Please Select a Gift."); } break; } case "GiftItem.giN": { GiftPackageItem giftPackage = (GiftPackageItem)e.Row.Item; if (giftPackage.GiftItem == null) { UIHelper.ShowMessage("Please select a Gift"); e.Cancel = true; } break; } default: { dgr.RowEditEnding -= dgr_RowEditEnding; if (_isCellCancel) { dgr.CancelEdit(); } else { dgr.CommitEdit(); dgr.Items.Refresh(); GridHelper.SelectRow(dgr, dgr.SelectedIndex); } dgr.RowEditEnding += dgr_RowEditEnding; _isCellCancel = false; break; } } } else if (dgr.Name == "dgrGiftInPack") { GiftPackageItem giftPackage = (GiftPackageItem)e.Row.Item; if (giftPackage.GiftItem == null) { e.Cancel = true; } } } }