public static void CheckSessionAccessList(AccessSubType accessSubType, RadButton btnPrint, RadButton btnAdd, RadButton btnNew, RadButton btnSave, RadButton btnCancel, RadGridView grid) { if (Session.CurrentUser.Role.IsAdmin) return; AccessControl ac = Session.CurrentUser.Role.AccessControlList[accessSubType]; if (!ac.AccessPrint) { if (btnPrint != null) btnPrint.Hide(); } if (!ac.AccessRemove) { if (grid != null) grid.Columns.RemoveAt(grid.Columns.Count() - 1); } if (!ac.AccessInsert) { if (btnAdd != null) btnAdd.Hide(); if (btnNew != null) btnNew.Hide(); } if (!ac.AccessChange) { if (btnSave != null) btnSave.Hide(); if (btnCancel != null) btnCancel.Hide(); } }
public static void PrintPreview(RadGridView grdData) { if (grdData.Rows.Count <= 0) { MessageBox.Show(@"No Datas To Be Printed.", @"Print", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } try { var rpd = new RadPrintDocument { Margins = new Margins(10, 10, 10, 10), DefaultPageSettings = { PaperSize = new PaperSize("A4", 850, 1100) }, AssociatedObject = grdData }; var dialog = new RadPrintPreviewDialog { ThemeName = grdData.ThemeName, Document = rpd, StartPosition = FormStartPosition.CenterScreen }; dialog.ShowDialog(); } catch (Exception e) { MessageBox.Show(@"Error While Printing Document." + Environment.NewLine + e.Message, @"Print", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } }
/// <summary> /// Constructor /// </summary> public MainForm() { InitializeComponent(); clicksCount = 0; allClicksCount = 0; circlesCount = 0; _countLabel = countLabel; _allCountLabel = allCountLabel; _circlesLabel = circlesLabel; _countLabel.Text = strCount + clicksCount; _allCountLabel.Text = strAllCount + allClicksCount; _circlesLabel.Text = strCircles + circlesCount; isClickerStarted = false; isPosClickerStarted = false; ghkCkickerTab = new GlobalHotkey((int)HotKeys.StartClickerTab, Constants.ALT + Constants.SHIFT, Keys.O, this); ghkAddPosClickerTab = new GlobalHotkey((int)HotKeys.AddPosClcikerTab, Constants.ALT + Constants.SHIFT, Keys.K, this); ghkStartPosClickerTab = new GlobalHotkey((int)HotKeys.StartPosClickerTab, Constants.ALT + Constants.SHIFT, Keys.L, this); _posGridView = posGridView; clickerSpinEditor.Value = clickDelay; posClickerSpinEditor.Value = posClickDelay; }
private static RadSpreadsheet CreateSpreadsheet(RadGridView grid) { return new RadSpreadsheet() { Workbook = CreateWorkBook(grid) }; }
public GridViewRowDoubleClickHandler(RadGridView gridView) { MouseButtonEventHandler handler = (sender, args) => { var row = sender as GridViewRow; if (row != null && row.IsSelected) { var methodName = GetMethodName(gridView); var dataContextType = gridView.DataContext.GetType(); var method = dataContextType.GetMethod(methodName); if (method == null) { throw new MissingMethodException(methodName); } method.Invoke(gridView.DataContext, null); } }; gridView.RowLoaded += (s, e) => { e.Row.MouseDoubleClick += handler; }; gridView.RowUnloaded += (s, e) => { e.Row.MouseDoubleClick -= handler; }; }
public ValidationBehavior(RadGridView gridView, bool isEnabled) { this.gridView = gridView; this.isValidationEnabled = isEnabled; this.gridView.CellValidating += this.GridView_CellValidating; }
/// <summary> /// 创建RadGridView /// </summary> /// <param name="structs">RadGridView列</param> /// <param name="itemsSource">数据源</param> /// <param name="headerName"></param> /// <returns></returns> public static RadGridView CreatDataGridView(Dictionary<string, string> structs, IEnumerable<object> itemsSource, string headerName) { var rgView = new RadGridView { ShowGroupPanel = false, AutoGenerateColumns = false, IsReadOnly = true, Name = headerName, RowIndicatorVisibility = Visibility.Collapsed }; foreach (var gvColumn in structs.Keys.Select(item => new GridViewDataColumn { Header = structs[item], IsFilterable = false, IsSortable = false, DataMemberBinding = new System.Windows.Data.Binding(item) })) { rgView.Columns.Add(gvColumn); } rgView.ItemsSource = itemsSource; return rgView; }
/// <summary> /// Converts the selected data to string for clipboard copy paste. /// </summary> /// <param name="grid">The gridview.</param> /// <returns>The formatted textual representation of the selected gridview cells.</returns> public static string ConvertSelectedDataToString(RadGridView grid) { var sb = new StringBuilder(); foreach (var h in grid.Columns) { sb.Append(h.Name + "\t"); } sb.Append("\n"); foreach (GridViewRowInfo t in grid.SelectedRows) { for (int cell = 0; cell < t.Cells.Count; cell++) { sb.Append(t.Cells[cell].Value != null ? t.Cells[cell].Value.ToString() : " --- "); sb.Append("\t"); } sb.Append("\n"); } return sb.ToString(); }
public ConfigurationPanelBehavior(RadGridView grid, FrameworkElement panel) { this.grid = grid; this.panel = panel; this.ActivatedRows = new ObservableCollection<MyBusinessObject>(); this.panel.LayoutUpdated += new EventHandler(panel_LayoutUpdated); }
public CustomFilterBehavior(RadGridView gridView, TextBox tb) { this.gridView = gridView; this.tb = tb; this.tb.TextChanged -= FilterValue_TextChanged; this.tb.TextChanged += FilterValue_TextChanged; }
public SelectedCellsBindingBehavior(RadGridView gridView, System.Windows.Controls.ListBox listBox) { this.gridView = gridView; this.listBox = listBox; this.listBox.ItemsSource = this.selectedCells; this.gridView.SelectedCellsChanged += gridView_SelectedCellsChanged; }
public BindingRowDetailsWidthBehavior(RadGridView grid) { this.gridView = grid; if(this.gridView != null) { this.gridView.LoadingRowDetails+=new EventHandler<Telerik.Windows.Controls.GridView.GridViewRowDetailsEventArgs>(OnLoadingRowDetails); } }
public ContextMenuBehavior(RadGridView grid, FrameworkElement contextMenu) { this.gridView = grid; this.contextMenu = contextMenu; (contextMenu as RadContextMenu).Opened += RadContextMenu_Opened; (contextMenu as RadContextMenu).ItemClick += RadContextMenu_ItemClick; }
public CustomFilterBehavior(RadGridView gridView, RadWatermarkTextBox textBlock, RadBusyIndicator busyIndicator) { this.gridView = gridView; this.textBlock = textBlock; this.busyIndicator = busyIndicator; this.textBlock.TextChanged -= this.OnTextBlockTextChanged; this.textBlock.TextChanged += this.OnTextBlockTextChanged; }
private static RowReorderBehavior GetAttachedBehavior(RadGridView gridview) { if (!instances.ContainsKey(gridview)) { instances[gridview] = new RowReorderBehavior(); instances[gridview].AssociatedObject = gridview; } return instances[gridview]; }
public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Windows.Application.LoadComponent(this, new System.Uri("/Procbel.Apps.Silverlight.Modules.Incidencias;component/Views/IncidenciasOverview" + "UserControl.xaml", System.UriKind.Relative)); this.LayoutRoot = ((System.Windows.Controls.Grid)(this.FindName("LayoutRoot"))); this.attachmentGrid = ((RadGridView)(this.FindName("attachmentGrid"))); }
public ConfigurationPanelBehavior(RadGridView gridView, FrameworkElement panel) { this.RemoveChildTableDefinitionsCommand = new RemoveChildTableDefinitonsCommand(this); this.RestoreChildTableDefinitionsCommand = new RestoreChildTableDefinitonsCommand(this); this.gridView = gridView; this.controlPanel = panel; this.gridView.DataLoading += this.gridView_DataLoading; panel.LayoutUpdated += this.panel_LayoutUpdated; }
public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Windows.Application.LoadComponent(this, new System.Uri("/Procbel.Apps.Silverlight.Modules.Activities;component/Views/ActivitiesListUserCo" + "ntrol.xaml", System.UriKind.Relative)); this.LayoutRoot = ((System.Windows.Controls.Grid)(this.FindName("LayoutRoot"))); this.activitiesGrid = ((RadGridView)(this.FindName("activitiesGrid"))); this.Status = ((GridViewDataColumn)(this.FindName("Status"))); }
public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Windows.Application.LoadComponent(this, new System.Uri("/Procbel.Apps.Silverlight.Modules.Contacts;component/Views/ContactsListUserContro" + "l.xaml", System.UriKind.Relative)); this.LayoutRoot = ((System.Windows.Controls.Grid)(this.FindName("LayoutRoot"))); this.contactsDataSource = ((RadDomainDataSource)(this.FindName("contactsDataSource"))); this.gridView = ((RadGridView)(this.FindName("gridView"))); }
public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Windows.Application.LoadComponent(this, new System.Uri("/Procbel.Apps.Silverlight.Modules.Incidencias;component/Views/IncidenciasListUser" + "Control.xaml", System.UriKind.Relative)); this.LayoutRoot = ((System.Windows.Controls.Grid)(this.FindName("LayoutRoot"))); this.FilterBox = ((System.Windows.Controls.TextBox)(this.FindName("FilterBox"))); this.incidenciasGrid = ((RadGridView)(this.FindName("incidenciasGrid"))); this.radToggleButton = ((RadToggleButton)(this.FindName("radToggleButton"))); }
public ControlPanelBehavior(RadGridView gridView, FrameworkElement panel) { this.AddCommand = new UnboundMode.AddCommand(this); this.RemoveCommand = new UnboundMode.RemoveCommand(this); this.ClearCommand = new UnboundMode.ClearCommand(this); this.gridView = gridView; this.panel = panel; this.panel.LayoutUpdated += new EventHandler(panel_LayoutUpdated); FillGrid(); }
private void LoadTemplateIntoGridView(RadGridView gridView) { contentPresenter.IsHitTestVisible = false; contentPresenter.DataContext = this; contentPresenter.ContentTemplate = this.EmptyDataTemplate; Grid rootGrid = gridView.ChildrenOfType<Grid>().FirstOrDefault(); contentPresenter.SetValue(Grid.RowProperty, 2); contentPresenter.SetValue(Grid.RowSpanProperty, 2); contentPresenter.SetValue(Grid.ColumnSpanProperty, 2); contentPresenter.SetValue(Border.MarginProperty, new Thickness(0, 27, 0, 0)); rootGrid.Children.Add(contentPresenter); }
public static void ExportExcelProcess(RadGridView _gv) { SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "Excel files (*.xls)|*.xls|All files (*.*)|*.*"; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { string strFileName = saveFileDialog1.FileName; ExportToExcelML exporter = new ExportToExcelML(_gv);//RadGridView1) string fileName = strFileName; exporter.RunExport(fileName); } }
public static void fillGridViewSettings(RadGridView gridView) { string name = gridView.Name + "_"; foreach (GridViewDataColumn column in gridView.Columns) { try { column.Width = setting[name + column.Name]; } catch { column.Width = 50; } } }
public static void SetPortapapeles(KeyEventArgs e, RadGridView grid) { if (e.KeyCode == Keys.F11) { if (grid.SelectedRows.Count > 0) { var titulo = grid.SelectedRows.FirstOrDefault().DataBoundItem as TituloDto; if (titulo == null) return; Clipboard.SetText(string.Format("{0};{1};{2}", titulo.NombreTitulo, titulo.AutorNombre, titulo.EditorialNombre)); MessageBoxDisplayService _messageBoxDisplayServic = new MessageBoxDisplayService(); _messageBoxDisplayServic.ShowSuccess("Se copió al Portapapeles"); } } }
public MyBehavior(CheckBox source) { this.checkBox = source; this.checkBox.Unloaded += checkBox_Unloaded; checkBox.Dispatcher.BeginInvoke(new Action (() => { grid = checkBox.ParentOfType<RadGridView>(); groupRow = checkBox.ParentOfType<GridViewGroupRow>(); if (grid != null && groupRow != null) { groupRow.Unloaded += groupRow_Unloaded; this.UpdateIsChecked(groupRow.Group); } if (grid != null) { grid.SelectionMode = System.Windows.Controls.SelectionMode.Extended; grid.SelectionUnit = GridViewSelectionUnit.FullRow; checkBox.Click += clickHandler = (s, e) => { grid.SelectionChanged -= grid_SelectionChanged; if (checkBox.IsChecked == true) { grid.Select(this.GetSubGroupItems(((GroupViewModel)checkBox.DataContext).Group)); } else { grid.Unselect(this.GetSubGroupItems(((GroupViewModel)checkBox.DataContext).Group)); } grid.SelectionChanged += grid_SelectionChanged; }; groupRow.DataContextChanged += dataContextChangedHandler = (s, e) => { this.UpdateIsChecked(e.NewValue as IGroup); }; } } )); }
//LLenar Grid Con array Objetos public void FillGrid(List<object[]> objs, RadGridView r,bool band=false) { r.Columns.Clear(); r.Rows.Clear(); foreach (object objectse in objs[0]) { r.Columns.Add(objectse.ToString()); } Image img = Resources.agenda.ToBitmap(); if (band) { GridViewImageColumn imageColumn = new GridViewImageColumn("Imprimir"); imageColumn.MaxWidth = 80; imageColumn.MinWidth = 80; imageColumn.HeaderTextAlignment = ContentAlignment.MiddleCenter; imageColumn.HeaderText = "Imprimir"; r.Columns.Add(imageColumn); } for (int i = 1; i < objs.Count; i++) { if (band) { object[] objsnnew = new object[objs[i].Length + 1]; for (int j = 0; j < objs[i].Length; j++) { objsnnew[j] = objs[i][j]; } objsnnew[objs[0].Length] = img; r.Rows.Add(objsnnew); } else { r.Rows.Add(objs[i]); } } r.TableElement.RowHeight = 55; r.TableElement.TableHeaderHeight = 35; }
public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Windows.Application.LoadComponent(this, new System.Uri("/Procbel.Apps.Silverlight.Modules.Contacts;component/Views/ContactOpportunitiesUs" + "erControl.xaml", System.UriKind.Relative)); this.uc = ((System.Windows.Controls.UserControl)(this.FindName("uc"))); this.LayoutRoot = ((System.Windows.Controls.Grid)(this.FindName("LayoutRoot"))); this.VisualStateGroup = ((System.Windows.VisualStateGroup)(this.FindName("VisualStateGroup"))); this.Normal = ((System.Windows.VisualState)(this.FindName("Normal"))); this.Edit = ((System.Windows.VisualState)(this.FindName("Edit"))); this.opportunitiesGrid = ((RadGridView)(this.FindName("opportunitiesGrid"))); this.overlayRectangle = ((System.Windows.Shapes.Rectangle)(this.FindName("overlayRectangle"))); this.border = ((System.Windows.Controls.Border)(this.FindName("border"))); this.dataForm = ((RadDataForm)(this.FindName("dataForm"))); this.productsDataSource = ((RadDomainDataSource)(this.FindName("productsDataSource"))); }
public UCGridFilter(RadGridView filteredGrid, string filteringField) { InitializeComponent(); gridView = filteredGrid; filter.IsFilterEditor = false; filter.PropertyName = filteringField; GridViewDataColumn column = filteredGrid.Columns[filteringField]; switch (column.DataType.Name) { case "String": filter.Operator = FilterOperator.Contains; break; default: break; } }
public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Windows.Application.LoadComponent(this, new System.Uri("/Procbel.Apps.Silverlight.Modules.Companies;component/Views/CompanyActivitiesUser" + "Control.xaml", System.UriKind.Relative)); this.uc = ((System.Windows.Controls.UserControl)(this.FindName("uc"))); this.LayoutRoot = ((System.Windows.Controls.Grid)(this.FindName("LayoutRoot"))); this.VisualStateGroup = ((System.Windows.VisualStateGroup)(this.FindName("VisualStateGroup"))); this.Normal = ((System.Windows.VisualState)(this.FindName("Normal"))); this.Add = ((System.Windows.VisualState)(this.FindName("Add"))); this.Edit = ((System.Windows.VisualState)(this.FindName("Edit"))); this.scheduleView = ((RadScheduleView)(this.FindName("scheduleView"))); this.activitiesGrid = ((RadGridView)(this.FindName("activitiesGrid"))); this.Status = ((GridViewDataColumn)(this.FindName("Status"))); this.overlayRectangle = ((System.Windows.Shapes.Rectangle)(this.FindName("overlayRectangle"))); this.border = ((System.Windows.Controls.Border)(this.FindName("border"))); this.dialog = ((Procbel.Apps.Silverlight.Helpers.ScheduleViewCustomDialogHost)(this.FindName("dialog"))); }
public GridViewClipboardCustomBehavior_SL(RadGridView grid) { this.grid = grid; }
internal static void ExportRadGridViewToExcelML(RadGridView gvwToExport, bool showColumnHeaders, bool showColumnFooters) { ExportRadGridViewToExcelML(gvwToExport, showColumnHeaders, showColumnFooters, true); }
public static string ZzGetStringValueByFieldName(this RadGridView grid, string FieldName) => ZzGetStringValue(grid, Standard.GetGridColumnName(FieldName));
public static void BuildAnalogousGrid(ViewAnalogousVM anagousReactionVM, RadGridView ConsolidatedGrid, bool NewAnalogous) { try { ConsolidatedGrid.ItemsSource = null; ConsolidatedGrid.Columns.Clear(); ConsolidatedGrid.ColumnGroups.Clear(); ConsolidatedGrid.Items.Clear(); var mainViewModel = ((MainWindow)(App.Current.MainWindow)).DataContext as MainVM; if (anagousReactionVM != null) { #region Add Columns var maxProducts = mainViewModel.TanVM.ReactionParticipants.OfReactionOfType(anagousReactionVM.SelectedMasterReaction.Id, ParticipantType.Product).Select(p => p.DisplayOrder).Distinct().OrderByDescending(o => o).FirstOrDefault(); var maxStage = anagousReactionVM.AnalogousReactions.Any() ? anagousReactionVM.AnalogousReactions[0]?.Stages.Count : 0; GridViewDataColumn ReactionIdColumn = new Telerik.Windows.Controls.GridViewDataColumn(); ReactionIdColumn.Header = RXNID; ReactionIdColumn.DataMemberBinding = new Binding(RXNID); ReactionIdColumn.IsVisible = false; ConsolidatedGrid.Columns.Add(ReactionIdColumn); var snoNumberColumn = new Telerik.Windows.Controls.GridViewDataColumn(); snoNumberColumn.Header = SNO; snoNumberColumn.DataMemberBinding = new Binding(SNO); snoNumberColumn.IsReadOnly = true; snoNumberColumn.Width = 40; ConsolidatedGrid.Columns.Add(snoNumberColumn); var rxnColumn = new Telerik.Windows.Controls.GridViewDataColumn(); rxnColumn.Header = RXN; rxnColumn.DataMemberBinding = new Binding(RXN); rxnColumn.IsReadOnly = true; rxnColumn.Width = 100; ConsolidatedGrid.Columns.Add(rxnColumn); var cvtColumn = new Telerik.Windows.Controls.GridViewDataColumn(); cvtColumn.Header = REACTIONCVT; cvtColumn.DataMemberBinding = new Binding(REACTIONCVT); cvtColumn.IsReadOnly = true; cvtColumn.Width = 100; ConsolidatedGrid.Columns.Add(cvtColumn); var FreeTextColumn = new Telerik.Windows.Controls.GridViewDataColumn(); FreeTextColumn.Header = REACTIONFREETEXT; FreeTextColumn.DataMemberBinding = new Binding(REACTIONFREETEXT); FreeTextColumn.IsReadOnly = true; FreeTextColumn.Width = 100; ConsolidatedGrid.Columns.Add(FreeTextColumn); //for (int productIndex = 1; productIndex <= maxProducts; productIndex++) //{ GridViewDataColumn ProductIdColumn = new Telerik.Windows.Controls.GridViewDataColumn(); ProductIdColumn.Header = PRODUCT + "ID"; ProductIdColumn.DataMemberBinding = new Binding(PRODUCT + "ID"); ProductIdColumn.IsVisible = false; ConsolidatedGrid.Columns.Add(ProductIdColumn); var ProductColumn = new Telerik.Windows.Controls.GridViewDataColumn(); ProductColumn.Header = PRODUCT; ProductColumn.DataMemberBinding = new Binding(PRODUCT); ProductColumn.ColumnGroupName = PRODUCT; ProductColumn.Width = 100; ConsolidatedGrid.Columns.Add(ProductColumn); //} //for (int productIndex = 1; productIndex <= maxProducts; productIndex++) //{ var YieldColumn = new Telerik.Windows.Controls.GridViewDataColumn(); YieldColumn.Header = YIELD; YieldColumn.DataMemberBinding = new Binding(YIELD); YieldColumn.ColumnGroupName = YIELD; YieldColumn.Width = 45; ConsolidatedGrid.Columns.Add(YieldColumn); //} for (int stageIndex = 1; stageIndex <= maxStage; stageIndex++) { var stageGroup = new Telerik.Windows.Controls.GridViewColumnGroup { Name = STAGE + stageIndex }; ConsolidatedGrid.ColumnGroups.Add(stageGroup); foreach (var participantName in ParticipantHeaders) { GridViewDataColumn IdColumn = new Telerik.Windows.Controls.GridViewDataColumn(); IdColumn.Header = participantName + stageIndex + "ID"; IdColumn.DataMemberBinding = new Binding(participantName + stageIndex + "ID"); IdColumn.ColumnGroupName = stageGroup.Name; IdColumn.IsVisible = false; ConsolidatedGrid.Columns.Add(IdColumn); var participantColumn = new Telerik.Windows.Controls.GridViewDataColumn(); participantColumn.Header = participantName; participantColumn.ColumnGroupName = stageGroup.Name; participantColumn.DataMemberBinding = new Binding(participantName + stageIndex); participantColumn.Width = 70; ConsolidatedGrid.Columns.Add(participantColumn); } var Temperature = new Telerik.Windows.Controls.GridViewDataColumn(); Temperature.Header = TEMPERATURE; Temperature.ColumnGroupName = stageGroup.Name; Temperature.DataMemberBinding = new Binding(TEMPERATURE + stageIndex); Temperature.Width = 70; Temperature.IsReadOnly = true; ConsolidatedGrid.Columns.Add(Temperature); var Pressure = new Telerik.Windows.Controls.GridViewDataColumn(); Pressure.Header = PRESSURE; Pressure.ColumnGroupName = stageGroup.Name; Pressure.DataMemberBinding = new Binding(PRESSURE + stageIndex); Pressure.Width = 70; Pressure.IsReadOnly = true; ConsolidatedGrid.Columns.Add(Pressure); var Time = new Telerik.Windows.Controls.GridViewDataColumn(); Time.Header = TIME; Time.ColumnGroupName = stageGroup.Name; Time.DataMemberBinding = new Binding(TIME + stageIndex); Time.Width = 70; Time.IsReadOnly = true; ConsolidatedGrid.Columns.Add(Time); var pH = new Telerik.Windows.Controls.GridViewDataColumn(); pH.Header = PH; pH.ColumnGroupName = stageGroup.Name; pH.DataMemberBinding = new Binding(PH + stageIndex); pH.Width = 70; pH.IsReadOnly = true; ConsolidatedGrid.Columns.Add(pH); var StageCVT = new Telerik.Windows.Controls.GridViewDataColumn(); StageCVT.Header = STAGECVT + stageIndex; StageCVT.ColumnGroupName = stageGroup.Name; StageCVT.DataMemberBinding = new Binding(STAGECVT + stageIndex); StageCVT.Width = 70; StageCVT.IsReadOnly = true; ConsolidatedGrid.Columns.Add(StageCVT); var StageFreeText = new Telerik.Windows.Controls.GridViewDataColumn(); StageFreeText.Header = STAGEFREETEXT; StageFreeText.ColumnGroupName = stageGroup.Name; StageFreeText.DataMemberBinding = new Binding(STAGEFREETEXT + stageIndex); StageFreeText.Width = 70; StageFreeText.IsReadOnly = true; ConsolidatedGrid.Columns.Add(StageFreeText); } ConsolidatedGrid.FrozenColumnCount = 9; foreach (Telerik.Windows.Controls.GridViewDataColumn c in ConsolidatedGrid.Columns) { c.IsFilterable = false; } #endregion foreach (var c in ConsolidatedGrid.Columns) { var dc = (GridViewDataColumn)c; } int rowCount = 1; List <IDictionary <String, Object> > rows = new List <IDictionary <String, Object> >(); foreach (var reaction in anagousReactionVM.AnalogousReactions) { var row = (IDictionary <String, Object>) new ExpandoObject(); row[AG] = 1; row[SNO] = rowCount++; row[RXN] = reaction.Name; row[RXNID] = reaction.Id; if (NewAnalogous) { var reactionRSN = anagousReactionVM.Rsns.Where(p => p.Reaction.Id == reaction.Id && p.Stage == null).OrderBy(p => p.DisplayOrder); row[PRODUCT] = string.Empty; row[PRODUCT + "ID"] = string.Empty; row[YIELD] = string.Empty; row[REACTIONFREETEXT] = !string.IsNullOrEmpty(string.Join(",", reactionRSN.Select(rsn => rsn.FreeText).ToList())) ? string.Join(",", reactionRSN.Select(rsn => rsn.FreeText).ToList()) : string.Empty; row[REACTIONCVT] = !string.IsNullOrEmpty(string.Join(",", reactionRSN.Select(rsn => rsn.CvtText).ToList())) ? string.Join(",", reactionRSN.Select(rsn => rsn.CvtText).ToList()) : string.Empty; } else { var products = mainViewModel.TanVM.ReactionParticipants.OfReactionOfType(reaction.Id, ParticipantType.Product).OrderBy(p => p.DisplayOrder); var reactionRSN = mainViewModel.TanVM.Rsns.Where(p => p.Reaction.Id == reaction.Id && p.Stage == null).OrderBy(p => p.DisplayOrder); row[PRODUCT] = string.Join(",", products.Select(n => n.Num).ToList()); row[PRODUCT + "ID"] = string.Join(",", products.Select(n => n.Id).ToList()); row[YIELD] = string.Join(",", products.Select(n => n.Yield).ToList()); row[REACTIONFREETEXT] = !string.IsNullOrEmpty(string.Join(",", reactionRSN.Select(rsn => rsn.FreeText).ToList())) ? string.Join(",", reactionRSN.Select(rsn => rsn.FreeText).ToList()) : string.Empty; row[REACTIONCVT] = !string.IsNullOrEmpty(string.Join(",", reactionRSN.Select(rsn => rsn.CvtText).ToList())) ? string.Join(",", reactionRSN.Select(rsn => rsn.CvtText).ToList()) : string.Empty; } if (reaction.Stages != null && reaction.Stages.Any()) { int stageCount = 1; foreach (var stage in reaction.Stages) { row.Add(STAGEID + stageCount, stage.Id); var stageRsn = NewAnalogous ? anagousReactionVM.Rsns.Where(p => p.Reaction.Id == reaction.Id && p.Stage != null && p.Stage.Id == stage.Id).OrderBy(p => p.DisplayOrder) : mainViewModel.TanVM.Rsns.Where(p => p.Reaction.Id == reaction.Id && p.Stage != null && p.Stage.Id == stage.Id).OrderBy(p => p.DisplayOrder); foreach (var participantType in ParticipantHeaders) { if (participantType.Equals(ParticipantType.Reactant.ToString()) && !NewAnalogous) { var reactants = mainViewModel.TanVM.ReactionParticipants.OfReactionAndStage(reaction.Id, stage.Id).Where(p => p.ParticipantType.ToString() == participantType).OrderBy(p => p.DisplayOrder); var csvNames = String.Join(",", reactants.Select(r => r.Num)); row.Add(participantType.ToString() + stageCount, csvNames); row.Add(participantType.ToString() + stageCount + "ID", String.Join(",", reactants.Select(r => r.Id))); } else { var otherParticipants = anagousReactionVM.ReactionParticipants.OfReactionAndStage(reaction.Id, stage.Id).Where(p => p.ParticipantType.ToString() == participantType).OrderBy(p => p.DisplayOrder); if (otherParticipants.Count() > 0) { var csvNames = String.Join(",", otherParticipants.Select(r => r.Num)); row.Add(participantType.ToString() + stageCount, csvNames); row.Add(participantType.ToString() + stageCount + "ID", String.Join(",", otherParticipants.Select(r => r.Id))); } else { row.Add(participantType.ToString() + stageCount, string.Empty); row.Add(participantType.ToString() + stageCount + "ID", string.Empty); } } } row.Add(TIME + stageCount, string.Join(",", stage.Conditions.Select(t => t.Time).ToList())); row.Add(TEMPERATURE + stageCount, string.Join(",", stage.Conditions.Select(t => t.Temperature).ToList())); row.Add(PRESSURE + stageCount, string.Join(",", stage.Conditions.Select(t => t.Pressure).ToList())); row.Add(PH + stageCount, string.Join(",", stage.Conditions.Select(t => t.PH).ToList())); row.Add(STAGECVT + stageCount, string.Join(",", stageRsn.Select(t => t.CvtText).ToList())); row.Add(STAGEFREETEXT + stageCount, string.Join(",", stageRsn.Select(t => t.FreeText).ToList())); stageCount++; } } rows.Add(row); } ConsolidatedGrid.ItemsSource = rows; } } catch (Exception ex) { Log.This(ex); throw; } }
public GridViewClipboardContextMenu(RadGridView grid) { this.grid = grid; }
public static void SearchGridByMemberNationalCode_LoadGridBriefly(string text, RadGridView gridView, DataBaseDataContext connection) { var query = connection.Members.OrderByDescending(a => a.ID).Where(a => a.NationalCode.Contains(text)).Select( a => new { id = a.ID, code = a.Code, fullName = a.FirstName + " " + a.LastName, nationalCode = a.NationalCode }); gridView.DataSource = query; gridView.Columns[1].IsVisible = false; gridView.Columns[2].Width = (int)Math.Ceiling(0.2 * gridView.Width); gridView.Columns[2].HeaderText = "کد عضویت"; gridView.Columns[3].Width = (int)Math.Ceiling(0.5 * gridView.Width); gridView.Columns[3].HeaderText = "نام و نام خانوادگی"; gridView.Columns[4].Width = (int)Math.Ceiling(0.2 * gridView.Width);; gridView.Columns[4].HeaderText = "کد ملی"; for (int i = 0; i < gridView.RowCount; i++) { gridView.Rows[i].Cells[0].Value = i + 1; } }
public static int ZzGetIntegerValueByFieldName(this RadGridView grid, string FieldName, int DefaultValue) => CxConvert.ToInt32(ZzGetStringValue(grid, Standard.GetGridColumnName(FieldName)), DefaultValue);
public abstract void SetupView(RadGridView dgv, DataTable table);
private void grid_CommandCellClick(object sender, EventArgs e) { try { GridCommandCellElement gridCell = (GridCommandCellElement)sender; string name = gridCell.ColumnInfo.Name.ToLower(); GridViewRowInfo row = gridCell.RowElement.RowInfo; long id = row.Cells[COLS.Id].Value.ToLong(); if (name == "update") { RadGridView grid = gridCell.GridControl; if (grid.CurrentRow != null && grid.CurrentRow is GridViewDataRowInfo) { objeCustomBO = new SetCustomFaresBO(); objeCustomBO.GetByPrimaryKey(id); if (objeCustomBO.Current != null) { objeCustomBO.Current.Pickup = grid.CurrentRow.Cells[COLS.Pickup].Value.ToString(); objeCustomBO.Current.Destination = grid.CurrentRow.Cells[COLS.Destination].Value.ToString(); objeCustomBO.Current.ViaPoints = grid.CurrentRow.Cells[COLS.ViaPoints].Value.ToStr(); objeCustomBO.Current.DriverFares = grid.CurrentRow.Cells[COLS.DriverFares].Value.ToDecimal(); objeCustomBO.Current.DriverRtnFares = grid.CurrentRow.Cells[COLS.DriverRtnFares].Value.ToDecimal(); objeCustomBO.Current.CustomerFares = grid.CurrentRow.Cells[COLS.CustomerFares].Value.ToDecimal(); objeCustomBO.Current.CustomerRtnFares = grid.CurrentRow.Cells[COLS.CustomerRtnFares].Value.ToDecimal(); objeCustomBO.Current.CompanyFares = grid.CurrentRow.Cells[COLS.CompanyFares].Value.ToDecimal(); objeCustomBO.Current.CompanyRtnFares = grid.CurrentRow.Cells[COLS.CompanyRtnFares].Value.ToDecimal(); if (grid.CurrentRow.Cells[COLS.CompanyId].Value != null) { objeCustomBO.Current.CompanyId = grid.CurrentRow.Cells[COLS.CompanyId].Value.ToInt(); } objeCustomBO.CheckDataValidation = false; objeCustomBO.Save(); // SetDisplayRecords(); } } } else if (name == "delete") { if (DialogResult.Yes == RadMessageBox.Show("Are you sure you want to delete Selected Booking(s) ? ", "", MessageBoxButtons.YesNo, RadMessageIcon.Question)) { objeCustomBO = new SetCustomFaresBO(); objeCustomBO.GetByPrimaryKey(id); objeCustomBO.Delete(objeCustomBO.Current); grdFares.Refresh(); row.Delete(); // SetDisplayRecords(); } } } catch { } }
/// <summary> /// Set 'CommandParameter' Dependency Property /// </summary> /// <param name="dataGrid">RadGridView</param> /// <param name="command">ICommand</param> public static void SetCommandParameter(RadGridView dataGrid, object parameter) { dataGrid.SetValue(CommandParameterProperty, parameter); }
private void grid_CommandCellClick(object sender, EventArgs e) { GridCommandCellElement gridCell = (GridCommandCellElement)sender; string name = gridCell.ColumnInfo.Name.ToLower(); GridViewRowInfo row = gridCell.RowElement.RowInfo; long id = row.Cells["Id"].Value.ToLong(); int driverId = row.Cells["DriverId"].Value.ToInt(); bool rtn = false; if (name == "btndelete") { if (DialogResult.Yes == RadMessageBox.Show("Are you sure you want to delete a Booking ? ", "", MessageBoxButtons.YesNo, RadMessageIcon.Question)) { RadGridView grid = gridCell.GridControl; grid.CurrentRow.Delete(); } } else if (name == "btnrecall") { if (row.Cells["Status"].Value.ToStr() == "POB" || row.Cells["Status"].Value.ToStr() == "STC") { ENUtils.ShowMessage("Job cannot be Re-Call as driver is on " + row.Cells["Status"].Value.ToStr() + " Status."); return; } else if (row.Cells["StatusId"].Value.ToInt() == Enums.BOOKINGSTATUS.DISPATCHED || row.Cells["StatusId"].Value.ToInt() == Enums.BOOKINGSTATUS.CANCELLED) { if (General.GetQueryable <Booking>(null).Count(c => c.Id == id && (c.AcceptedDateTime != null || c.Fleet_Driver != null && c.Fleet_Driver.HasPDA == true)) > 0) { ENUtils.ShowMessage("Job cannot be Re-Call as driver is on " + row.Cells["Status"].Value.ToStr() + " Status."); return; } } if (DialogResult.Yes == RadMessageBox.Show("Are you sure you want to Re-Call a Booking ? ", "", MessageBoxButtons.YesNo, RadMessageIcon.Question)) { new Thread(delegate() { General.ReCallBooking(id, driverId); }).Start(); } else { return; } } else if (name == "btnredespatch") { rtn = General.ShowDespatchForm(General.GetObject <Booking>(c => c.Id == id)); } if (name == "btnrecall" || name == "btnredespatch") { if (name == "btnredespatch" && rtn == false) { return; } Thread.Sleep(500); PopulateData(); (Application.OpenForms.OfType <Form>().FirstOrDefault(c => c.Name == "frmBookingDashBoard") as frmBookingDashBoard).RefreshActiveData(); // General.RefreshListWithoutSelected<frmBookingDashBoard>("frmBookingDashBoard1"); } }
public MySelectedItemsBindingBehavior(RadGridView grid, INotifyCollectionChanged selectedItems) { this.grid = grid; this.selectedItems = selectedItems; }
/// <summary> /// Set 'Command' Dependency Property /// </summary> /// <param name="dataGrid">RadGridView</param> /// <param name="command">ICommand</param> public static void SetCommand(RadGridView dataGrid, ICommand command) { dataGrid.SetValue(CommandProperty, command); }
private static RadGridViewSelectionChangedCommandBehaviour GetOrCreateBehavior(RadGridView dataGrid) { var behavior = dataGrid.GetValue(ClickCommandBehaviorProperty) as RadGridViewSelectionChangedCommandBehaviour; if (behavior == null) { behavior = new RadGridViewSelectionChangedCommandBehaviour(dataGrid); dataGrid.SetValue(ClickCommandBehaviorProperty, behavior); } return(behavior); }
public CustomGroupingBehavior(RadGridView grid) { this.grid = grid; }
public static void ZzSetGridMainProperties(this RadGridView grid, int RowHeight = 30, bool AllowRowResize = false) { grid.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.None; grid.TableElement.RowHeight = RowHeight; grid.AllowRowResize = AllowRowResize; }
public CustomSortingBehavior(RadGridView grid) { this.grid = grid; }
/// <summary> /// Get 'CommandParameter' Dependency Property /// </summary> /// <param name="dataGrid">RadGridView</param> /// <returns>ICommand</returns> public static object GetCommandParameter(RadGridView dataGrid) { return(dataGrid.GetValue(CommandParameterProperty) as object); }
/// <summary> /// Get 'Command' Dependency Property /// </summary> /// <param name="dataGrid">RadGridView</param> /// <returns>ICommand</returns> public static ICommand GetCommand(RadGridView dataGrid) { return(dataGrid.GetValue(CommandProperty) as ICommand); }
/// <summary> /// method for adding rows to exported pdf /// </summary> /// <param name="table"></param> /// <param name="items"></param> /// <param name="columns"></param> /// <param name="grid"></param> private void AddDataRows(Table table, IList items, IList <GridViewBoundColumnBase> columns, RadGridView grid) { for (int i = 0; i < items.Count; i++) { TableRow row = new TableRow(); if (grid.GroupDescriptors.Count() > 0) { TableCell indentCell = new TableCell(); indentCell.PreferredWidth = new TableWidthUnit(grid.GroupDescriptors.Count() * 20); indentCell.Background = Colors.White; row.Cells.Add(indentCell); } for (int j = 0; j < columns.Count(); j++) { TableCell cell = new TableCell(); object value = null; if (j == 0) { value = columns[j].GetValueForItem(items[i]) != null ? (columns[j].GetValueForItem(items[i])) : null; } else if (j == columns.Count - 1) { value = ((items[i]) as RelativePerformanceData) != null ? ((items[i]) as RelativePerformanceData).AggregateCountryAlpha.ToString() : null; } else { value = columns[j].GetValueForItem(items[i]) != null ? ((columns[j].GetValueForItem(items[i])) as RelativePerformanceCountrySpecificData).Alpha.ToString() : null; } AddCellValue(cell, value != null ? value.ToString() : string.Empty); cell.PreferredWidth = new TableWidthUnit((float)columns[j].ActualWidth); cell.Background = Colors.White; row.Cells.Add(cell); } table.Rows.Add(row); } }
public void TearDown(object uiControl) { gridView.GroupDescriptors.Clear(); gridView = null; }
public void ExportWithHeader(object parameter, Header header) { RadGridView grid = parameter as RadGridView; if (grid != null) { grid.ElementExporting -= this.ElementExporting; grid.ElementExporting += this.ElementExporting; string extension = ""; ExportFormat format = ExportFormat.Html; switch (SelectedExportFormat) { case "Excel": extension = "xls"; format = ExportFormat.Html; break; case "ExcelML": extension = "xml"; format = ExportFormat.ExcelML; break; case "Word": extension = "doc"; format = ExportFormat.Html; break; case "Csv": extension = "csv"; format = ExportFormat.Csv; break; } SaveFileDialog dialog = new SaveFileDialog(); dialog.DefaultExt = extension; dialog.Filter = String.Format("{1} files (*.{0})|*.{0}|All files (*.*)|*.*", extension, SelectedExportFormat); dialog.FilterIndex = 1; if (dialog.ShowDialog() == true) { using (Stream stream = dialog.OpenFile()) { GridViewExportOptions exportOptions = new GridViewExportOptions(); exportOptions.Format = format; exportOptions.ShowColumnFooters = false; exportOptions.ShowColumnHeaders = true; exportOptions.ShowGroupFooters = true; exportOptions.Encoding = Encoding.UTF8; grid.Export(stream, exportOptions); byte[] bs = new byte[stream.Length]; stream.Seek(0, SeekOrigin.Begin); stream.Read(bs, 0, bs.Length); string str = Encoding.UTF8.GetString(bs, 0, bs.Length); string str1 = str.Insert(str.IndexOf('>', 0) + 1, createHeaderStr(header)); byte[] bys = Encoding.UTF8.GetBytes(str1); stream.Seek(0, SeekOrigin.Begin); stream.Write(bys, 0, bys.Length); stream.Flush(); } } } }
public static void LoadGridJoinSocialNetworkAccountJoinPhoneNumber(RadGridView gridView, DataBaseDataContext connection) { var joinQuery = connection.Members.Join( connection.SocialNetworkAccounts.Where(a => a.Status == true), member => member.ID, social_network_account => social_network_account.MemberID, (mem, account) => new { mem, account }).Join(connection.PhoneNumbers.Where(a => a.Status == true), memsocial => memsocial.mem.ID, phone => phone.MemberID, (memsocial, phone) => new { id = memsocial.mem.ID, code = memsocial.mem.Code, fullName = memsocial.mem.FirstName + " " + memsocial.mem.LastName, nationalCode = memsocial.mem.NationalCode, birthDate = BTM.Date.ConvertToPersianDate(memsocial.mem.BirthDate), sex = memsocial.mem.Sex, level = memsocial.mem.Level.Title, socialNetAccount = memsocial.account.Account, phoneNum = phone.Number }); //var query = connection.Members.Where(a => a.Level == level). // Select(a => new // { // id = a.ID, // code = a.Code, // fullName = a.FirstName + " " + a.LastName, // nationalCode = a.NationalCode, // birthDate = BTM.Date.ConvertToPersianDate(a.BirthDate), // sex = a.Sex, // level = a.Level.Title // }); gridView.DataSource = joinQuery; gridView.Columns[1].IsVisible = false; gridView.Columns[2].Width = 70; gridView.Columns[2].HeaderText = "کد عضویت"; gridView.Columns[3].Width = 150; gridView.Columns[3].HeaderText = "نام و نام خانوادگی"; gridView.Columns[4].Width = 100; gridView.Columns[4].HeaderText = "کد ملی"; gridView.Columns[5].Width = 100; gridView.Columns[5].HeaderText = "تاریخ تولد"; gridView.Columns[6].Width = 110; gridView.Columns[6].HeaderText = "جنیست"; gridView.Columns[7].Width = 90; gridView.Columns[7].HeaderText = "نوع عضویت"; gridView.Columns[8].Width = 150; gridView.Columns[8].HeaderText = "اکانت شبکه اجتماعی"; gridView.Columns[9].Width = 110; gridView.Columns[9].HeaderText = "شماره تماس"; for (int i = 0; i < gridView.RowCount; i++) { gridView.Rows[i].Cells[0].Value = i + 1; } }
/// <summary> /// adding group rows to exported pdf /// </summary> /// <param name="table"></param> /// <param name="group"></param> /// <param name="columns"></param> /// <param name="grid"></param> private void AddGroupRow(Table table, QueryableCollectionViewGroup group, IList <GridViewBoundColumnBase> columns, RadGridView grid) { TableRow row = new TableRow(); int level = GetGroupLevel(group); if (level > 0) { TableCell cell = new TableCell(); cell.PreferredWidth = new TableWidthUnit(level * 20); cell.Background = Colors.White; row.Cells.Add(cell); } TableCell aggregatesCell = new TableCell(); aggregatesCell.Background = Colors.White; aggregatesCell.ColumnSpan = columns.Count() + (grid.GroupDescriptors.Count() > 0 ? 1 : 0) - (level > 0 ? 1 : 0); AddCellValue(aggregatesCell, group.Key != null ? group.Key.ToString() : string.Empty); foreach (AggregateResult result in group.AggregateResults) { AddCellValue(aggregatesCell, result.FormattedValue != null ? result.FormattedValue.ToString() : string.Empty); } row.Cells.Add(aggregatesCell); table.Rows.Add(row); if (group.HasSubgroups) { for (int i = 0; i < group.Subgroups.Count(); i++) { AddGroupRow(table, group.Subgroups[i] as QueryableCollectionViewGroup, columns, grid); } } else { for (int i = 0; i < group.ItemCount; i++) { AddDataRows(table, group.Items, columns, grid); } } }
public void ExportWithHeader(List <object> parameter, List <Header> headers, List <bool> showFooter) { string extension = ""; ExportFormat format = ExportFormat.Html; switch (SelectedExportFormat) { case "Excel": extension = "xls"; format = ExportFormat.Html; break; case "ExcelML": extension = "xml"; format = ExportFormat.ExcelML; break; case "Word": extension = "doc"; format = ExportFormat.Html; break; case "Csv": extension = "csv"; format = ExportFormat.Csv; break; } SaveFileDialog dialog = new SaveFileDialog(); dialog.DefaultExt = extension; dialog.Filter = String.Format("{1} files (*.{0})|*.{0}|All files (*.*)|*.*", extension, SelectedExportFormat); dialog.FilterIndex = 1; if (dialog.ShowDialog() == true) { using (Stream stream = dialog.OpenFile()) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < parameter.Count; i++) { string header = createHeaderStr(headers[i]); RadGridView grid = parameter[i] as RadGridView; if (grid != null) { grid.ElementExporting -= this.ElementExporting; grid.ElementExporting += this.ElementExporting; GridViewExportOptions exportOptions = new GridViewExportOptions(); exportOptions.Format = format; exportOptions.ShowColumnFooters = showFooter[i]; exportOptions.ShowColumnHeaders = true; exportOptions.ShowGroupFooters = true; exportOptions.Encoding = Encoding.UTF8; using (MemoryStream ms = new MemoryStream()) { grid.Export(ms, exportOptions); byte[] bs = new byte[ms.Length]; ms.Seek(0, SeekOrigin.Begin); ms.Read(bs, 0, bs.Length); string str = Encoding.UTF8.GetString(bs, 0, bs.Length); string str1 = str.Insert(str.IndexOf('>', 0) + 1, header); sb.Append(str1); } } } byte[] bysall = Encoding.UTF8.GetBytes(sb.ToString()); stream.Seek(0, SeekOrigin.Begin); stream.Write(bysall, 0, bysall.Length); stream.Flush(); } } }
private void RadGridView_DataLoaded(object sender, EventArgs e) { RadGridView grid = (sender as RadGridView); grid.ExpandAllGroups(); }
/// <summary> ///导出数据为Excel /// </summary> /// <param name="dataGridViewSource">需要导出的数据</param> /// <param name="saveFileName">导出文件的名称</param> /// <returns></returns> public static string ImprotDataToExcel(RadGridView dataGridViewSource, string saveFileName) { //string DownLoadPath = System.IO.Directory.GetCurrentDirectory() + "\\template\\模版.xlsx"; if (dataGridViewSource.Rows.Count == 0) { MessageBox.Show("该表数据为空!!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information); return(""); } SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "Excel文件 (*.xlsx)|*.xlsx|(*.xls)|*.xls"; saveFileDialog1.FilterIndex = 1; saveFileDialog1.RestoreDirectory = true; //获取时分秒 string exportDate = DateTime.Now.ToString("yyyyMMddHHmmss"); //名称后面自动加入时分秒 saveFileDialog1.FileName += saveFileName + exportDate + ".xlsx"; DialogResult dialogResult = saveFileDialog1.ShowDialog(); // 如果点击了取消,则退出方法 if (dialogResult == DialogResult.Cancel) { return(""); } //try //{ // // 根据模版生成一个空白的Excel文件 // //System.IO.File.Copy(DownLoadPath, saveFileDialog1.FileName); //} //catch (Exception ex) //{ // MessageBox.Show("复制Excel文件出错" + ex.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Error); //} try { //SpreadsheetDocument.Create(saveFileDialog1.FileName,DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook,true); //SpreadsheetDocument.Open(saveFileDialog1.FileName, true) using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Create(saveFileDialog1.FileName, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook, true)) { #region 新建一个WorkSheet //WorkSheet的名称 string sheetName = saveFileName; // create the workbook spreadSheet.AddWorkbookPart(); spreadSheet.WorkbookPart.Workbook = new Workbook(); // create the worksheet spreadSheet.WorkbookPart.AddNewPart <WorksheetPart>(); spreadSheet.WorkbookPart.WorksheetParts.First().Worksheet = new Worksheet(); SharedStringTablePart m_SharedStringTablePart = spreadSheet.WorkbookPart.AddNewPart <SharedStringTablePart>(); // create sheet data SheetData m_SheetData = new SheetData(); spreadSheet.WorkbookPart.WorksheetParts.First().Worksheet.AppendChild(m_SheetData); // create row //spreadSheet.WorkbookPart.WorksheetParts.First().Worksheet.First().AppendChild(new Row()); //// create cell with data //spreadSheet.WorkbookPart.WorksheetParts.First().Worksheet.First().First().AppendChild(new Cell() { CellValue = new CellValue("100") }); //Add Data Row row1 = new Row() { RowIndex = 1 }; Cell cell1 = new Cell() { CellReference = "A1" }; int index = InsertSharedStringItem("Sun", m_SharedStringTablePart); cell1.CellValue = new CellValue(index.ToString()); cell1.DataType = new EnumValue <CellValues>(CellValues.SharedString); row1.Append(cell1); m_SheetData.Append(row1); // save worksheet spreadSheet.WorkbookPart.WorksheetParts.First().Worksheet.Save(); // create the worksheet to workbook relation spreadSheet.WorkbookPart.Workbook.AppendChild(new Sheets()); spreadSheet.WorkbookPart.Workbook.GetFirstChild <Sheets>().AppendChild(new Sheet() { Id = spreadSheet.WorkbookPart.GetIdOfPart(spreadSheet.WorkbookPart.WorksheetParts.First()), SheetId = 1, Name = sheetName }); spreadSheet.WorkbookPart.Workbook.Save(); #endregion var sheetData = spreadSheet.GetFirstSheetData(); //设置单元格样式等于第一条样式 //OpenXmlHelper.CellStyleIndex = 1; char OneColumn = Convert.ToChar('A');//第一列都是从A开始的 // 去除列表中隐藏的列 RadGridView newDataSouce = dataGridViewSource; for (int i = dataGridViewSource.Columns.Count - 1; i >= 0; i--) { if (!dataGridViewSource.Columns[i].IsVisible) { //删除重复的项 newDataSouce.Columns.Remove(dataGridViewSource.Columns[i]); } } //不存在模板时就补充字段名称 for (var i = 0; i < newDataSouce.Columns.Count; i++) { if (newDataSouce.Columns[i].IsVisible) { OneColumn = Convert.ToChar('A' + i); //填写列的名称(暂时还是数据库中的英文) sheetData.SetCellValue(OneColumn.ToString() + 1, newDataSouce.Columns[i].HeaderText); } } if (dataGridViewSource.Rows.Count > 0) { for (var j = 0; j < newDataSouce.Rows.Count; j++) { OneColumn = Convert.ToChar('A'); for (var k = 0; k < newDataSouce.Columns.Count; k++) { //if (!newDataSouce.Rows[j].Cells[k].Visible) continue; OneColumn = Convert.ToChar('A' + k); //一个个填写值 sheetData.SetCellValue(OneColumn.ToString() + (j + 2), newDataSouce.Rows[j].Cells[k].Value); } } } MessageBox.Show("导出成功!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (Exception ex) { MessageBox.Show("导出Excel文件出错" + ex.Message); } return(""); }
private void MoveRows(RadGridView targetGrid, RadGridView dragGrid, IList <GridViewRowInfo> dragRows, int index) { dragGrid.BeginUpdate(); targetGrid.BeginUpdate(); for (int i = dragRows.Count - 1; i >= 0; i--) { GridViewRowInfo row = dragRows[i]; if (row is GridViewSummaryRowInfo) { continue; } if (targetGrid.DataSource == null) { //unbound scenario GridViewRowInfo newRow = targetGrid.Rows.NewRow(); foreach (GridViewCellInfo cell in row.Cells) { if (newRow.Cells[cell.ColumnInfo.Name] != null) { newRow.Cells[cell.ColumnInfo.Name].Value = cell.Value; } } targetGrid.Rows.Insert(index, newRow); row.IsSelected = false; dragGrid.Rows.Remove(row); } else if (typeof(DataSet).IsAssignableFrom(targetGrid.DataSource.GetType())) { //bound to a dataset scenario var sourceTable = ((DataSet)dragGrid.DataSource).Tables[0]; var targetTable = ((DataSet)targetGrid.DataSource).Tables[0]; var newRow = targetTable.NewRow(); foreach (GridViewCellInfo cell in row.Cells) { newRow[cell.ColumnInfo.Name] = cell.Value; } sourceTable.Rows.Remove(((DataRowView)row.DataBoundItem).Row); targetTable.Rows.InsertAt(newRow, index); } else if (typeof(IList).IsAssignableFrom(targetGrid.DataSource.GetType())) { //bound to a list of objects scenario var targetCollection = (IList)targetGrid.DataSource; var sourceCollection = (IList)dragGrid.DataSource; sourceCollection.Remove(row.DataBoundItem); targetCollection.Add(row.DataBoundItem); } else { throw new ApplicationException("Unhandled Scenario"); } index++; } dragGrid.EndUpdate(true); targetGrid.EndUpdate(true); }
public void UnitChanged(ComboBox cbBitsToUse, ComboBox cbUnit, RadGridView rgv, Button btnExport, TextBox tbExportPath) { viewProcessor.PopulateGrid(rgv, btnExport, cbUnit, null, tbExportPath); }
/// <summary> /// method for pdf exporting /// </summary> /// <param name="grid"></param> /// <returns></returns> private RadDocument CreateDocument(RadGridView grid) { List <GridViewBoundColumnBase> columns = (from c in grid.Columns.OfType <GridViewBoundColumnBase>() orderby c.DisplayIndex select c).ToList(); Table table = new Table(); RadDocument document = new RadDocument(); Telerik.Windows.Documents.Model.Section section = new Telerik.Windows.Documents.Model.Section(); section.Blocks.Add(table); document.Sections.Add(section); if (grid.ShowColumnHeaders) { TableRow headerRow = new TableRow(); if (grid.GroupDescriptors.Count() > 0) { TableCell indentCell = new TableCell(); indentCell.PreferredWidth = new TableWidthUnit(grid.GroupDescriptors.Count() * 20); indentCell.Background = Colors.Gray; headerRow.Cells.Add(indentCell); } for (int i = 0; i < columns.Count(); i++) { TableCell cell = new TableCell(); cell.Background = Colors.White; AddCellValue(cell, columns[i].Header.ToString()); cell.PreferredWidth = new TableWidthUnit((float)columns[i].ActualWidth); headerRow.Cells.Add(cell); } table.Rows.Add(headerRow); } if (grid.Items.Groups != null) { for (int i = 0; i < grid.Items.Groups.Count(); i++) { AddGroupRow(table, grid.Items.Groups[i] as QueryableCollectionViewGroup, columns, grid); } } else { AddDataRows(table, grid.Items, columns, grid); } if (grid.ShowColumnFooters) { TableRow footerRow = new TableRow(); for (int i = 0; i < columns.Count(); i++) { TableCell cell = new TableCell(); cell.Background = Colors.Gray; string value = ((columns[i].Footer) as TextBlock) != null ? ((columns[i].Footer) as TextBlock).Text.ToString() : columns[i].Footer.ToString(); AddCellValue(cell, value != null ? value.ToString() : string.Empty); cell.PreferredWidth = new TableWidthUnit((float)columns[i].ActualWidth); footerRow.Cells.Add(cell); } table.Rows.Add(footerRow); } return(document); }