/// <summary> /// Asserts that all columns are of the expected classes. /// </summary> /// <param name="expectedColumnTypes">The column types.</param> /// <param name="actualDataGridView">The view.</param> /// <exception cref="AssertionException">Thrown when a column is not of the /// expected class or there is a mismatch in the number of columns.</exception> public static void AssertColumnTypes(IEnumerable <Type> expectedColumnTypes, DataGridView actualDataGridView) { int expectedColumnTypesCount = expectedColumnTypes.Count(); Assert.AreEqual(expectedColumnTypesCount, actualDataGridView.ColumnCount); for (var i = 0; i < expectedColumnTypesCount; i++) { DataGridViewColumn column = actualDataGridView.Columns[i]; Type expectedColumnType = expectedColumnTypes.ElementAt(i); Assert.True(column.GetType().Implements(expectedColumnType), "Column type mismatch." + Environment.NewLine + $"Expected: {expectedColumnType.FullName}" + Environment.NewLine + $"Actual: {column.GetType().FullName}"); } }
private void CreateColumnFilter(DataGridViewColumn c) { if (!mAutoCreateFilters) { return; } //Raise the event about column filter creation ColumnFilterEventArgs e = new ColumnFilterEventArgs(c, null); if (ColumnFilterAdding != null) { ColumnFilterAdding(this, e); } //if not provided, by an event handler, proceed with standard filter creation if (e.ColumnFilter == null) { Type DataType = null; if (c.DataPropertyName != "") { DataType = mBoundDataView.Table.Columns[c.DataPropertyName].DataType; switch (c.GetType().Name) { case "DataGridViewComboBoxColumn": e.ColumnFilter = new DgvComboBoxColumnFilter(); break; case "DataGridViewCheckBoxColumn": e.ColumnFilter = new DgvCheckBoxColumnFilter(); break; case "DataGridViewTextBoxColumn": if (DataType == typeof(DateTime)) { e.ColumnFilter = new DgvDateColumnFilter(); } else { e.ColumnFilter = new DgvTextBoxColumnFilter(); } break; case "DataGridViewImageColumn": e.ColumnFilter = new DgvComboBoxImageColumnFilter(); break; } } } mColumnFilterList[c.Index] = e.ColumnFilter; if (e.ColumnFilter != null) // == null when non-data column { if (ColumnFilterAdded != null) { ColumnFilterAdded(this, e); } e.ColumnFilter.Init(this, FilterHost, c, mBoundDataView); } }
void DgvData_CellContentClick(object sender, DataGridViewCellEventArgs e) { DataGridViewColumn col = this.pagedDgvSupplier.DgvData.Columns[e.ColumnIndex]; if (col.GetType() == typeof(DataGridViewLinkColumn)) { String link = StringUtil.GetSafeString(this.pagedDgvSupplier.DgvData.Rows[e.RowIndex].Cells[e.ColumnIndex].Value); System.Diagnostics.Process.Start(link); } }
private void FormatColumns() { //IsFormattingComplete = false; for (int i = 0; i < GridView.Columns.Count; i++) { for (int ii = 0; ii < DataGridViewColumns.Length; ii++) { if (GridView.Columns[i].Name == DataGridViewColumns[ii].Name) { DataGridViewColumn target = GridView.Columns[i]; DataGridViewColumn source = DataGridViewColumns[ii]; // Available properties target.HeaderText = source.HeaderText; target.HeaderCell.Style.Alignment = source.DefaultCellStyle.Alignment; target.Visible = source.Visible; // AutoSizeMode must be 'None' to set widths target.AutoSizeMode = DataGridViewAutoSizeColumnMode.None; // Resetting default MinimumWidth target.MinimumWidth = source.MinimumWidth == 5 ? ColumnProperties.MinimumColumnWidth : source.MinimumWidth; target.Width = source.Width; // Individually auto-sizing columns can be very cpu intensive target.AutoSizeMode = source.AutoSizeMode; target.FillWeight = source.FillWeight; target.DefaultCellStyle = source.DefaultCellStyle; target.SortMode = source.SortMode; // Special Formatting // Fixed Length Digit - Warning: This will fire DataBindingComplete on each iteration if (Regex.IsMatch(source.DefaultCellStyle.Format, @"^[dD]\d+$")) { for (int j = 0; j < GridView.RowCount; j++) { if (int.TryParse(GridView.Rows[j].Cells[i].Value.ToString(), out int result)) { GridView.Rows[j].Cells[i].Value = result.ToString(source.DefaultCellStyle.Format); } } } // Making text cells non-editable target.ReadOnly = true; if (target.GetType().Equals(typeof(DataGridViewCheckBoxColumn))) { target.ReadOnly = false; } } } } IsFormattingComplete = true; }
public void Add() { DataGridViewColumnCollection c; c = (new DataGridView()).Columns; c.Add("A", "B"); DataGridViewColumn col = c [0]; Assert.AreEqual("DataGridViewTextBoxColumn { Name=A, Index=0 }", col.ToString(), "T3"); Assert.AreEqual("DataGridViewTextBoxColumn", col.GetType().Name, "G2"); Assert.AreEqual(DataGridViewAutoSizeColumnMode.NotSet, col.AutoSizeMode, "#A col.AutoSizeMode"); Assert.IsNotNull(col.CellTemplate, "#A col.CellTemplate"); Assert.IsNotNull(col.CellType, "#A col.CellType"); Assert.IsNull(col.ContextMenuStrip, "#A col.ContextMenuStrip"); Assert.IsNotNull(col.DataGridView, "#A col.DataGridView"); Assert.AreEqual(@"", col.DataPropertyName, "#A col.DataPropertyName"); Assert.IsNotNull(col.DefaultCellStyle, "#A col.DefaultCellStyle"); Assert.IsNotNull(col.DefaultHeaderCellType, "#A col.DefaultHeaderCellType"); Assert.AreEqual(false, col.Displayed, "#A col.Displayed"); Assert.AreEqual(0, col.DisplayIndex, "#A col.DisplayIndex"); Assert.AreEqual(0, col.DividerWidth, "#A col.DividerWidth"); Assert.AreEqual(100, col.FillWeight, "#A col.FillWeight"); Assert.AreEqual(false, col.Frozen, "#A col.Frozen"); Assert.AreEqual(true, col.HasDefaultCellStyle, "#A col.HasDefaultCellStyle"); Assert.IsNotNull(col.HeaderCell, "#A col.HeaderCell"); Assert.AreEqual(@"B", col.HeaderText, "#A col.HeaderText"); Assert.AreEqual(0, col.Index, "#A col.Index"); Assert.AreEqual(DataGridViewAutoSizeColumnMode.None, col.InheritedAutoSizeMode, "#A col.InheritedAutoSizeMode"); Assert.IsNotNull(col.InheritedStyle, "#A col.InheritedStyle"); Assert.AreEqual(false, col.IsDataBound, "#A col.IsDataBound"); Assert.AreEqual(5, col.MinimumWidth, "#A col.MinimumWidth"); Assert.AreEqual(@"A", col.Name, "#A col.Name"); Assert.AreEqual(false, col.ReadOnly, "#A col.ReadOnly"); Assert.AreEqual(DataGridViewTriState.True, col.Resizable, "#A col.Resizable"); Assert.AreEqual(false, col.Selected, "#A col.Selected"); Assert.IsNull(col.Site, "#A col.Site"); Assert.AreEqual(DataGridViewColumnSortMode.Automatic, col.SortMode, "#A col.SortMode"); Assert.AreEqual(DataGridViewElementStates.Visible, col.State, "#A col.State"); Assert.IsNull(col.Tag, "#A col.Tag"); Assert.AreEqual(@"", col.ToolTipText, "#A col.ToolTipText"); Assert.IsNull(col.ValueType, "#A col.ValueType"); Assert.AreEqual(true, col.Visible, "#A col.Visible"); Assert.AreEqual(100, col.Width, "#A col.Width"); }
private void m_events_CellContentClick(object sender, DataGridViewCellEventArgs e) { DataGridView grid = (DataGridView)sender; if (e.RowIndex == -1 || e.ColumnIndex == -1) { return; } DataGridViewColumn column = grid.Columns[e.ColumnIndex]; if (column.GetType() != typeof(DataGridViewLinkColumn)) { return; } ProcessView processView = null; DataGridViewCell cell = grid.Rows[e.RowIndex].Cells[e.ColumnIndex]; if (column.Name == m_colProcess.Name) { processView = new ProcessView(System.Convert.ToUInt32(cell.Value), 0); } else if (column.Name == m_colChildProcess.Name) { processView = new ProcessView(System.Convert.ToUInt32(cell.Value), 0); } else if (column.Name == m_colObjectID.Name) { processView = new ProcessView(0, System.Convert.ToUInt64(cell.Value)); } if (processView != null) { processView.ShowDialog(this); } }
private string getCmnParam(Control ctrl) { string str = ""; foreach (Control control in ctrl.Controls) { if (!control.Visible || control.Tag != null && (control.Tag.ToString().Equals("9999") || control.Tag.ToString().Equals("999") || control.Tag.ToString().Equals("99999"))) { continue; } string name = control.GetType().Name; string str1 = name; if (name != null) { switch (str1) { case "TextBox": case "DateTimePicker": { str = string.Concat(str, string.Format("{0};", control.Text)); continue; } case "ComboBox": case "ComBox": { str = string.Concat(str, control.Text, control.Tag); continue; } case "Label": { str = string.Concat(str, control.Text, control.Tag); continue; } case "NumericUpDown": { str = string.Concat(str, ((NumericUpDown)control).Text.ToString(), control.Tag); continue; } case "TrackBar": { int value = ((TrackBar)control).Value; str = string.Concat(str, value.ToString(), control.Tag); continue; } case "CheckBox": { str = string.Concat(str, string.Format("{0}:{1};", control.Text, this.getChkText(((CheckBox)control).Checked))); continue; } case "RadioButton": { str = string.Concat(str, string.Format("{0}:{1};", control.Text, this.getChkText(((RadioButton)control).Checked))); continue; } case "CheckedListBox": { IEnumerator enumerator = ((CheckedListBox)control).CheckedItems.GetEnumerator(); try { while (enumerator.MoveNext()) { System.Web.UI.WebControls.ListItem current = (System.Web.UI.WebControls.ListItem)enumerator.Current; str = string.Concat(str, string.Format("{0}:{1};", current.Text, this.getChkText(true))); } continue; } finally { IDisposable disposable = enumerator as IDisposable; if (disposable != null) { disposable.Dispose(); } } break; } case "DataGridView": { DataGridView dataGridView = (DataGridView)control; string str2 = ""; bool flag = false; bool flag1 = false; IEnumerator enumerator1 = ((IEnumerable)dataGridView.Rows).GetEnumerator(); try { while (enumerator1.MoveNext()) { DataGridViewRow dataGridViewRow = (DataGridViewRow)enumerator1.Current; str2 = ""; flag1 = false; flag = false; IEnumerator enumerator2 = dataGridView.Columns.GetEnumerator(); try { while (enumerator2.MoveNext()) { DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)enumerator2.Current; if (!dataGridViewColumn.Visible) { continue; } if (dataGridViewColumn.Tag != null && dataGridViewColumn.Tag.Equals("Chk")) { flag1 = true; if (dataGridViewRow.Cells[dataGridViewColumn.Name].Value.ToString() == "1" || dataGridViewRow.Cells[dataGridViewColumn.Name].Value.ToString().ToLower() == "true") { flag = true; } } if (dataGridViewColumn.GetType().Name != "DataGridViewCheckBoxColumn") { if (string.IsNullOrEmpty(string.Concat(dataGridViewRow.Cells[dataGridViewColumn.Name].Value))) { continue; } str2 = string.Concat(str2, string.Format("{0}:{1};", dataGridViewColumn.HeaderText, dataGridViewRow.Cells[dataGridViewColumn.Name].Value)); } else { str2 = (dataGridViewRow.Cells[dataGridViewColumn.Name].Value.ToString() == "1" || dataGridViewRow.Cells[dataGridViewColumn.Name].Value.ToString().ToLower() == "true" ? string.Concat(str2, string.Format("{0}:{1};", dataGridViewColumn.HeaderText, this.getChkText(true))) : string.Concat(str2, string.Format("{0}:{1};", dataGridViewColumn.HeaderText, this.getChkText(false)))); } } } finally { IDisposable disposable1 = enumerator2 as IDisposable; if (disposable1 != null) { disposable1.Dispose(); } } if (flag1 && !flag) { continue; } str = string.Concat(str, str2); } continue; } finally { IDisposable disposable2 = enumerator1 as IDisposable; if (disposable2 != null) { disposable2.Dispose(); } } break; } case "ListView": { string str3 = ""; foreach (ListViewItem item in ((ListView)control).Items) { if (item.Tag == null) { continue; } str3 = string.Concat(str3, string.Format(",{0}", item.Tag.ToString())); } char[] chrArray = new char[] { ',' }; str = string.Concat(str, str3.Trim(chrArray)); continue; } case "CheckBoxList": { CheckBoxItem[] items = ((CheckBoxList)control).Items; for (int i = 0; i < (int)items.Length; i++) { CheckBox checkBox = items[i]; str = string.Concat(str, string.Format("{0}:{1};", checkBox.Text, this.getChkText(checkBox.Checked))); } continue; } case "IPAddressTextBox": { str = string.Concat(str, control.Text, control.Tag); continue; } } } if (control.Name == "grpCar") { continue; } str = string.Concat(str, this.getCmnParam(control)); } return(str.Replace(";", ";").Replace("|", "|")); }
public static void PrepareReport(Report nreport, DataGridView ngrid, DataGridViewPrintOptions opts) { const int DefaultScreenDPI = 142; int BOOL_WIDTH = 100; int BOOL_SEP = 20; if (nreport.SubReports[0].Sections.Count == 1) { nreport.SubReports[0].AddGroup("TOTAL"); } Section Detail = nreport.SubReports[0].Sections[nreport.SubReports[0].FirstDetail]; Section GroupHeader = nreport.SubReports[0].Sections[nreport.SubReports[0].FirstDetail - 1]; Section GroupFooter = nreport.SubReports[0].Sections[nreport.SubReports[0].LastDetail + 1]; string aliasname = nreport.DataInfo[0].Alias; int totalwidth = Detail.Width; int rowcount = ngrid.Rows.Count; if (opts.PrintSelected) { rowcount = ngrid.SelectedRows.Count; } SortedList <string, DataGridViewColumn> CampoColumna = new SortedList <string, DataGridViewColumn>(); List <DataGridViewColumn> Columnas = new List <DataGridViewColumn>(); SortedList <int, DataGridViewColumn> ColumnasString = new SortedList <int, DataGridViewColumn>(); SortedList <int, DataGridViewColumn> ColumnasBool = new SortedList <int, DataGridViewColumn>(); SortedList <int, DataGridViewColumn> ColumnasImage = new SortedList <int, DataGridViewColumn>(); List <string> Campos = new List <string>(); int idxcol = 0; if (opts.SelectedColumns.Count == 0) { foreach (DataGridViewColumn ncol in ngrid.Columns) { if (ncol.Visible) { Columnas.Add(ncol); idxcol++; CampoColumna.Add("CAMPO" + idxcol.ToString(), ncol); Campos.Add("CAMPO" + idxcol.ToString()); } } } else { foreach (DataGridViewColumn ncol in opts.SelectedColumns) { Columnas.Add(ncol); idxcol++; CampoColumna.Add("CAMPO" + idxcol.ToString(), ncol); Campos.Add("CAMPO" + idxcol.ToString()); } } int separator = 40; int level_separator = 200; int level_separator_gap = 50; // Calculate total width for the selected int maxwidth = 0; float screendpi = GraphicUtils.ScreenDPI(); float scalepixels = 1440f / screendpi; for (idxcol = 0; idxcol < Columnas.Count; idxcol++) { DataGridViewColumn ncol = Columnas[idxcol]; int newwidth = System.Convert.ToInt32(Math.Round(ncol.Width * scalepixels)); maxwidth = maxwidth + newwidth; if (idxcol < (Columnas.Count - 1)) { maxwidth = maxwidth + separator; } } List <ShapeItem> HorzShapes = new List <ShapeItem>(); int pagewidth = opts.PaperWidth(); pagewidth = pagewidth - nreport.LeftMargin - nreport.RightMargin; float fsize = ngrid.Font.Size; float fontscale = 1.0f; float scalesep = 1.0f; float newscale = 1.0f; if (opts.AdjustWidth) { newscale = (float)pagewidth / maxwidth; scalepixels = 1440f / screendpi * newscale; scalesep = newscale; if (maxwidth > pagewidth) { fontscale = newscale; fsize = fsize * fontscale; if (fsize <= 0) { fsize = 1; } } } // Calculate font size and width scale int rowheight = System.Convert.ToInt32(Math.Round(ngrid.RowTemplate.Height * scalepixels)); BOOL_WIDTH = System.Convert.ToInt32(BOOL_WIDTH * fontscale); BOOL_SEP = System.Convert.ToInt32(BOOL_SEP * fontscale); separator = System.Convert.ToInt32(separator * fontscale); level_separator = System.Convert.ToInt32(level_separator * fontscale); level_separator_gap = System.Convert.ToInt32(level_separator_gap * fontscale); GroupHeader.Height = rowheight; Detail.Height = rowheight; // Prepare datatable DataTable ntable = new DataTable(); idxcol = 0; int posx = 0; // Grey header ShapeItem sitem = new ShapeItem(nreport); sitem.Shape = ShapeType.Rectangle; sitem.BrushStyle = BrushType.Solid; sitem.PenStyle = Reportman.Drawing.PenType.Clear; sitem.BrushColor = GraphicUtils.IntegerFromColor(Color.FromArgb(200, 200, 200)); sitem.Height = rowheight; sitem.Align = PrintItemAlign.TopBottom; HorzShapes.Add(sitem); nreport.GenerateNewName(sitem); GroupHeader.Components.Add(sitem); sitem = new ShapeItem(nreport); sitem.Shape = ShapeType.VertLine; sitem.Height = rowheight; sitem.Align = PrintItemAlign.TopBottom; nreport.GenerateNewName(sitem); GroupHeader.Components.Add(sitem); if (opts.DrawBackGroundColors) { // Background color sitem = new ShapeItem(nreport); sitem.PrintCondition = aliasname + ".BACKCOLOR<>NULL"; sitem.BrushColorExpression = aliasname + ".BACKCOLOR"; sitem.Shape = ShapeType.Rectangle; sitem.Width = maxwidth; sitem.PenStyle = Reportman.Drawing.PenType.Clear; sitem.PosX = posx; sitem.Align = PrintItemAlign.TopBottom; Detail.Components.Add(sitem); HorzShapes.Add(sitem); } sitem = new ShapeItem(nreport);; sitem.Shape = ShapeType.HorzLine; sitem.Width = maxwidth; HorzShapes.Add(sitem); nreport.GenerateNewName(sitem); GroupHeader.Components.Add(sitem); sitem = new ShapeItem(nreport);; sitem.Shape = ShapeType.HorzLine; sitem.Width = maxwidth; HorzShapes.Add(sitem); nreport.GenerateNewName(sitem); GroupFooter.Components.Add(sitem); sitem = new ShapeItem(nreport);; sitem.Shape = ShapeType.HorzLine; sitem.Width = maxwidth; HorzShapes.Add(sitem); sitem.Align = PrintItemAlign.Bottom; nreport.GenerateNewName(sitem); GroupHeader.Components.Add(sitem); if (opts.VerticalLines) { sitem = new ShapeItem(nreport); sitem.Shape = ShapeType.VertLine; sitem.Height = rowheight; sitem.Align = PrintItemAlign.TopBottom; nreport.GenerateNewName(sitem); Detail.Components.Add(sitem); } string columnlevel = ""; for (idxcol = 0; idxcol < Columnas.Count; idxcol++) { DataGridViewColumn ncol = Columnas[idxcol]; DataGridViewContentAlignment cellalign = DataGridViewContentAlignment.NotSet; if (ngrid.DefaultCellStyle != null) { cellalign = ngrid.DefaultCellStyle.Alignment; } if (ncol.DefaultCellStyle != null) { cellalign = ncol.DefaultCellStyle.Alignment; } LabelItem litem = new LabelItem(nreport); SetAlignFromCellFormat(cellalign, litem); litem.VAlignment = TextAlignVerticalType.Top; if (litem.Alignment == TextAlignType.Left) { litem.Alignment = TextAlignType.Justify; } litem.Height = rowheight; litem.FontSize = System.Convert.ToInt16(fsize); nreport.GenerateNewName(litem); litem.Text = ncol.HeaderText; GroupHeader.Components.Add(litem); litem.Height = rowheight; litem.PosX = posx; litem.WordWrap = opts.WordWrap; litem.CutText = !opts.WordWrap; litem.Width = System.Convert.ToInt32(Math.Round(ncol.Width * scalepixels)); bool istextcolumn = false; istextcolumn = ncol is DataGridViewTextBoxColumn; if (!istextcolumn) { if (ncol is DataGridViewColumnAdvanced) { istextcolumn = true; } } TreeGridAdvanced ngridav; if (istextcolumn) { ntable.Columns.Add(Campos[idxcol], System.Type.GetType("System.String")); ColumnasString.Add(idxcol, ncol); if ((ncol is TreeGridAdvancedColumn) && (ngrid is TreeGridAdvanced)) { if (columnlevel == "") { columnlevel = "LEVEL"; } ngridav = (TreeGridAdvanced)ngrid; for (int idxlevel = 1; idxlevel <= ngridav.MaxLevel; idxlevel++) { // Add Image for level ImageItem imaitem = new ImageItem(nreport); imaitem.Expression = aliasname + ".IMAGE"; imaitem.PrintCondition = aliasname + ".LEVEL=" + idxlevel.ToString(); imaitem.Height = rowheight; imaitem.Align = PrintItemAlign.TopBottom; imaitem.Width = level_separator; imaitem.PosX = level_separator_gap + posx + level_separator * (idxlevel) - level_separator + level_separator_gap; imaitem.PosY = 0; imaitem.DrawStyle = ImageDrawStyleType.Full; imaitem.dpires = System.Convert.ToInt32(DefaultScreenDPI); nreport.GenerateNewName(imaitem); Detail.Components.Add(imaitem); // Add expression foreach level ExpressionItem exitem = new ExpressionItem(nreport); exitem.Expression = aliasname + "." + Campos[idxcol]; exitem.PrintCondition = aliasname + ".LEVEL=" + idxlevel.ToString(); exitem.WordWrap = opts.WordWrap; exitem.CutText = !opts.WordWrap; SetAlignFromCellFormat(cellalign, exitem); if (exitem.Alignment == TextAlignType.Left) { exitem.Alignment = TextAlignType.Justify; } exitem.VAlignment = TextAlignVerticalType.Top; exitem.FontSize = System.Convert.ToInt16(fsize); exitem.Height = rowheight; exitem.PosX = level_separator_gap * 2 + posx + level_separator * idxlevel; exitem.Height = rowheight; nreport.GenerateNewName(exitem); exitem.Width = litem.Width - level_separator * (idxlevel + 1); Detail.Components.Add(exitem); if (opts.DrawTreeLines) { // Last child line sitem = new ShapeItem(nreport); sitem.PrintCondition = "((" + aliasname + ".LEVEL=" + idxlevel.ToString() + ") AND (" + aliasname + ".LASTCHILD))"; sitem.Shape = ShapeType.VertLine; sitem.PenStyle = Reportman.Drawing.PenType.Dot; sitem.PosX = level_separator_gap + posx + level_separator * idxlevel - level_separator; sitem.Height = rowheight / 3; Detail.Components.Add(sitem); // Not last child horz line sitem = new ShapeItem(nreport); sitem.PrintCondition = "((" + aliasname + ".LEVEL=" + idxlevel.ToString() + ") AND (NOT (" + aliasname + ".LASTCHILD)))"; sitem.Shape = ShapeType.VertLine; sitem.PenStyle = Reportman.Drawing.PenType.Dot; sitem.PosX = level_separator_gap + posx + level_separator * idxlevel - level_separator; sitem.Align = PrintItemAlign.TopBottom; Detail.Components.Add(sitem); // Other parent lines sitem = new ShapeItem(nreport); sitem.PrintCondition = aliasname + ".LEVEL>" + idxlevel.ToString(); sitem.Shape = ShapeType.VertLine; sitem.Align = PrintItemAlign.TopBottom; sitem.PenStyle = Reportman.Drawing.PenType.Dot; sitem.PosX = level_separator_gap + posx + level_separator * idxlevel - level_separator; sitem.Height = rowheight / 2; Detail.Components.Add(sitem); // Horz arrow sitem = new ShapeItem(nreport); sitem.PrintCondition = aliasname + ".LEVEL=" + idxlevel.ToString(); sitem.PenStyle = Reportman.Drawing.PenType.Dot; sitem.Shape = ShapeType.HorzLine; sitem.PosX = level_separator_gap + posx + level_separator * idxlevel - level_separator; sitem.PosY = rowheight / 3; sitem.Width = level_separator / 2; Detail.Components.Add(sitem); } } } else { ExpressionItem exitem = new ExpressionItem(nreport); exitem.Expression = aliasname + "." + Campos[idxcol]; exitem.WordWrap = opts.WordWrap; exitem.CutText = !opts.WordWrap; SetAlignFromCellFormat(cellalign, exitem); if (exitem.Alignment == TextAlignType.Left) { exitem.Alignment = TextAlignType.Justify; } exitem.VAlignment = TextAlignVerticalType.Top; exitem.FontSize = System.Convert.ToInt16(fsize); exitem.Height = rowheight; exitem.PosX = posx; exitem.Height = rowheight; nreport.GenerateNewName(exitem); exitem.Width = litem.Width; Detail.Components.Add(exitem); } } else { if (ncol is DataGridViewImageColumn) { ColumnasImage.Add(idxcol, ncol); ntable.Columns.Add(Campos[idxcol], System.Type.GetType("System.Object")); ImageItem imaitem = new ImageItem(nreport); imaitem.Expression = aliasname + "." + Campos[idxcol]; imaitem.Height = rowheight; imaitem.Align = PrintItemAlign.TopBottom; imaitem.Width = litem.Width; imaitem.PosX = posx + separator; imaitem.PosY = 0; imaitem.DrawStyle = ImageDrawStyleType.Full; imaitem.dpires = System.Convert.ToInt32(DefaultScreenDPI); nreport.GenerateNewName(imaitem); Detail.Components.Add(imaitem); } else if (ncol is DataGridViewCheckBoxColumn) { ColumnasBool.Add(idxcol, ncol); ntable.Columns.Add(Campos[idxcol], System.Type.GetType("System.Boolean")); ShapeItem cuaditem = new ShapeItem(nreport); cuaditem.Shape = ShapeType.Rectangle; cuaditem.PrintCondition = aliasname + "." + Campos[idxcol] + "<>NULL"; //cuaditem.Align = PrintItemAlign.TopBottom; cuaditem.BrushStyle = BrushType.Clear; cuaditem.Height = rowheight; int shapepos = posx + (litem.Width / 2) - BOOL_WIDTH / 2; cuaditem.PosX = shapepos; cuaditem.PosY = BOOL_SEP; cuaditem.Width = BOOL_WIDTH; cuaditem.Height = BOOL_WIDTH; nreport.GenerateNewName(cuaditem); Detail.Components.Add(cuaditem); cuaditem = new ShapeItem(nreport); cuaditem.Shape = ShapeType.Oblique1; cuaditem.PrintCondition = aliasname + "." + Campos[idxcol]; //cuaditem.Align = PrintItemAlign.TopBottom; cuaditem.BrushStyle = BrushType.Clear; cuaditem.Height = rowheight; cuaditem.PosX = shapepos; cuaditem.PosY = BOOL_SEP; cuaditem.Width = BOOL_WIDTH; cuaditem.Height = BOOL_WIDTH; nreport.GenerateNewName(cuaditem); Detail.Components.Add(cuaditem); cuaditem = new ShapeItem(nreport); cuaditem.Shape = ShapeType.Oblique2; cuaditem.PrintCondition = aliasname + "." + Campos[idxcol]; //cuaditem.Align = PrintItemAlign.TopBottom; cuaditem.BrushStyle = BrushType.Clear; cuaditem.Height = rowheight; cuaditem.PosX = shapepos; cuaditem.PosY = BOOL_SEP; cuaditem.Width = BOOL_WIDTH; cuaditem.Height = BOOL_WIDTH; nreport.GenerateNewName(cuaditem); Detail.Components.Add(cuaditem); } else { throw new Exception("Tipo de columna no soportada:" + ncol.GetType().ToString()); } } posx = posx + litem.Width; posx = posx + System.Convert.ToInt32(separator * scalesep); if (opts.VerticalLines) { sitem = new ShapeItem(nreport); sitem.Shape = ShapeType.VertLine; sitem.PosX = posx; sitem.Height = rowheight; sitem.Align = PrintItemAlign.TopBottom; Detail.Components.Add(sitem); } sitem = new ShapeItem(nreport); sitem.Shape = ShapeType.VertLine; sitem.PosX = posx; sitem.Height = rowheight; sitem.Align = PrintItemAlign.TopBottom; GroupHeader.Components.Add(sitem); if (opts.HorizontalLines) { sitem = new ShapeItem(nreport); sitem.Shape = ShapeType.HorzLine; sitem.Width = maxwidth; HorzShapes.Add(sitem); //sitem.Align = PrintItemAlign.Top; Detail.Components.Add(sitem); sitem = new ShapeItem(nreport); sitem.PrintCondition = "CURRENTGROUP=0"; sitem.Shape = ShapeType.HorzLine; sitem.Width = maxwidth; HorzShapes.Add(sitem); sitem.Align = PrintItemAlign.Bottom; Detail.Components.Add(sitem); } } foreach (ShapeItem nshape in HorzShapes) { nshape.Width = posx; } int colbackground = 0; if (opts.DrawBackGroundColors) { ntable.Columns.Add("BACKCOLOR", System.Type.GetType("System.Int32")); colbackground = ntable.Columns.Count - 1; } if (columnlevel != "") { ntable.Columns.Add("IMAGE", System.Type.GetType("System.Object")); ntable.Columns.Add("LEVEL", System.Type.GetType("System.Int32")); ntable.Columns.Add("LASTCHILD", System.Type.GetType("System.Boolean")); } object[] nvalues = new object[ntable.Columns.Count]; int counter = 0; foreach (DataGridViewRow dgrow in ngrid.Rows) { if ((!opts.PrintSelected) || ((opts.PrintSelected) && (dgrow.Selected))) { foreach (int index in ColumnasString.Keys) { nvalues[index] = dgrow.Cells[ColumnasString[index].Index].FormattedValue; } foreach (int index in ColumnasBool.Keys) { nvalues[index] = dgrow.Cells[ColumnasBool[index].Index].Value; } foreach (int index in ColumnasImage.Keys) { MemoryStream mstream = GetImageStreamFromObject(dgrow.Cells[ColumnasImage[index].Index].Value); if (mstream != null) { nvalues[index] = mstream; } else { nvalues[index] = DBNull.Value; } } if (opts.DrawBackGroundColors) { DataGridViewCellStyle nstyle = null; if (!dgrow.DefaultCellStyle.BackColor.IsEmpty) { nstyle = dgrow.DefaultCellStyle; } if (nstyle == null) { if ((!ngrid.AlternatingRowsDefaultCellStyle.BackColor.IsEmpty)) { if (counter % 2 == 1) { nstyle = ngrid.AlternatingRowsDefaultCellStyle; } else if (!ngrid.DefaultCellStyle.BackColor.IsEmpty) { nstyle = ngrid.DefaultCellStyle; } } else { if (!ngrid.DefaultCellStyle.BackColor.IsEmpty) { nstyle = ngrid.AlternatingRowsDefaultCellStyle; } } } nvalues[colbackground] = DBNull.Value; if (nstyle != null) { if (nstyle.BackColor != Color.White) { if (nstyle.BackColor != Color.FromArgb(255, 255, 255)) { nvalues[colbackground] = GraphicUtils.IntegerFromColor(nstyle.BackColor); } } } } if (columnlevel.Length > 0) { TreeGridRow trow = (TreeGridRow)dgrow; MemoryStream mstream = GetImageStreamFromObject(trow.Image); if (mstream != null) { nvalues[nvalues.Length - 3] = mstream; } nvalues[nvalues.Length - 2] = trow.Level; nvalues[nvalues.Length - 1] = trow.IsLastSibling; /* * if (trow.Parent != null) * nvalues[nvalues.Length - 1] = ((trow.Node.Childs.Count == 0) || (!trow.Node.Expanded)) && (((TreeGridRow)dgrow).ChildIndex + 1) == ((TreeGridRow)dgrow).Parent.Node.Childs.Count; * else * { * nvalues[nvalues.Length - 1] = ((trow.Node.Childs.Count == 0) || (!trow.Node.Expanded)) && (((TreeGridAdvanced)ngrid).MainNode.Childs.Count == trow.ChildIndex + 1); * }*/ } ntable.Rows.Add(nvalues); counter++; } } nreport.DataInfo[aliasname].DataViewOverride = new DataView(ntable); //return meta; }
public static void DataGridViewtoExcel(DataGridView tmpDataTable, String strFileName) { if (tmpDataTable == null) { return; } string lvssss = Application.StartupPath + "\\Microsoft.Office.Interop.Excel.dll"; Assembly ass; object obj; //获取并加载DLL类库中的程序集 ass = Assembly.LoadFile(lvssss); //获取类的类型:必须使用名称空间+类名称 obj = ass.CreateInstance("Microsoft.Office.Interop.Excel.ApplicationClass"); Microsoft.Office.Interop.Excel.Application xlApp = obj as Microsoft.Office.Interop.Excel.Application; try { xlApp.Visible = true; xlApp.DefaultFilePath = ""; xlApp.DisplayAlerts = true; xlApp.SheetsInNewWorkbook = 1; Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true); Microsoft.Office.Interop.Excel._Worksheet xlSheet = xlBook.ActiveSheet as Microsoft.Office.Interop.Excel._Worksheet; object m_objOpt = System.Reflection.Missing.Value; int lv总行数 = tmpDataTable.Rows.Count; int lv总列数 = tmpDataTable.Columns.Count; object[,] objData = new Object[1, lv总列数]; int lv列_流水 = 0; for (int i = 0; i < tmpDataTable.Columns.Count; i++) { DataGridViewColumn dc = tmpDataTable.Columns[i]; if (dc.Visible == true && dc.GetType().Name != "DataGridViewButtonColumn") { objData[0, lv列_流水] = dc.HeaderText; lv列_流水++; } } xlSheet.Range["A1"].Select(); Microsoft.Office.Interop.Excel.Range m_objRange = null; m_objRange = xlSheet.get_Range("A1", m_objOpt); m_objRange = m_objRange.get_Resize(1, lv总列数); m_objRange.Value = objData; string lvTmpvalue; decimal lviTmpValue; int lv行数_每批导出最大行 = 2000; int lv复制总次数 = lv总行数 / lv行数_每批导出最大行 + 1; int lv行序号_相对总行数 = 0; //相对总行数 lv列_流水 = 0; int lv本次复制开始行 = 0; int lv本次可复制行数 = 0; while (lv行序号_相对总行数 < lv总行数) { lv本次复制开始行 = lv行序号_相对总行数; //如果剩余行数 大于 固定导出行数 则本次 导出 固定行数 lv本次可复制行数 = lv总行数 - lv行序号_相对总行数; if (lv本次可复制行数 > lv行数_每批导出最大行) { lv本次可复制行数 = lv行数_每批导出最大行; } int lv行_本次复制流水 = 0; objData = new Object[lv本次可复制行数, lv总列数]; while (lv行_本次复制流水 < lv本次可复制行数) { lv本次复制开始行 = lv行序号_相对总行数; lv列_流水 = 0; for (int j = 0; j < lv总列数; j++) { if (tmpDataTable.Columns[j].Visible == true && tmpDataTable.Columns[j].GetType().Name != "DataGridViewButtonColumn") { if (tmpDataTable.Rows[lv本次复制开始行 + lv行_本次复制流水].Cells[j].Value == null) { objData[lv行_本次复制流水, lv列_流水] = ""; } else { lvTmpvalue = tmpDataTable.Rows[lv本次复制开始行 + lv行_本次复制流水].Cells[j].Value.ToString().Trim(); if (decimal.TryParse(lvTmpvalue, out lviTmpValue)) { if (lviTmpValue == 0) { lvTmpvalue = ""; } } objData[lv行_本次复制流水, lv列_流水] = lvTmpvalue; } lv列_流水++; } } lv行_本次复制流水++; } lv行序号_相对总行数 = lv行序号_相对总行数 + lv本次可复制行数; m_objRange = xlSheet.get_Range(xlSheet.Cells[lv本次复制开始行 + 1, 1], xlSheet.Cells[lv本次复制开始行 + lv本次可复制行数, lv总列数]); //m_objRange = m_objRange.get_Resize(lv包含标题总行数, lv总列数); m_objRange.Value = objData; } xlBook.SaveCopyAs(System.Web.HttpUtility.UrlDecode(strFileName, System.Text.Encoding.UTF8)); xlBook.Saved = true; xlApp.Quit(); } catch// (Exception ex) { xlApp.Quit(); throw; } //Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); //引用Excel对象 //Microsoft.Office.Interop.Excel.Workbook book = excel.Workbooks.Add(strFileName); //引用Excel工作簿 //excel.Visible = true; //xlBook.SaveAs(strFileName,System.Text.Encoding.UTF8); }
public static void DataGridViewtoExcel(List <DataGridView> Grids4Excel, List <string> GridText, string strDefaultFileName) { if (Grids4Excel == null) { return; } if (Grids4Excel.Count == 0) { return; } SaveFileDialog saveFileDialog1 = new System.Windows.Forms.SaveFileDialog(); saveFileDialog1.FileName = strDefaultFileName; saveFileDialog1.DefaultExt = "*.xls"; saveFileDialog1.Filter = "Excel文件|*.xls"; if (saveFileDialog1.ShowDialog() != DialogResult.OK) { return; } int rowNum; int columnNum; int columnIndex = 1; int maxLineCount; string lvssss = Application.StartupPath + "\\Microsoft.Office.Interop.Excel.dll"; Assembly ass; object obj; ass = Assembly.LoadFile(lvssss); obj = ass.CreateInstance("Microsoft.Office.Interop.Excel.ApplicationClass"); Microsoft.Office.Interop.Excel.Application xlApp = obj as Microsoft.Office.Interop.Excel.Application; xlApp.Visible = true; xlApp.DefaultFilePath = ""; xlApp.DisplayAlerts = true; xlApp.SheetsInNewWorkbook = Grids4Excel.Count; object m_objOpt = System.Reflection.Missing.Value; Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true); DataGridView lvGrid; for (int lvSheetNo = 0; lvSheetNo < Grids4Excel.Count; lvSheetNo++) { lvGrid = Grids4Excel[lvSheetNo]; rowNum = lvGrid.Rows.Count; columnNum = lvGrid.Columns.Count; columnIndex = 1; maxLineCount = rowNum + 1; object[,] objData = new Object[maxLineCount, columnNum]; columnIndex = 0; for (int i = 0; i < lvGrid.Columns.Count; i++) { DataGridViewColumn dc = lvGrid.Columns[i]; if (dc.Visible == true && dc.GetType().Name != "DataGridViewButtonColumn") { objData[0, columnIndex] = dc.HeaderText; columnIndex++; } } string lvTmpvalue; decimal lviTmpValue; for (int r = 0; r < rowNum; r++) { columnIndex = 0; for (int j = 0; j < columnNum; j++) { if (lvGrid.Columns[j].Visible == true && lvGrid.Columns[j].GetType().Name != "DataGridViewButtonColumn") { if (lvGrid.Rows[r].Cells[j].Value == null) { objData[r + 1, columnIndex] = ""; } else { lvTmpvalue = lvGrid.Rows[r].Cells[j].Value.ToString().Trim(); if (decimal.TryParse(lvTmpvalue, out lviTmpValue)) { if (lviTmpValue == 0) { lvTmpvalue = ""; } } objData[r + 1, columnIndex] = lvTmpvalue; } columnIndex++; } } } //写入excel if (xlBook.Sheets.Count < lvSheetNo + 1) { xlBook.Sheets.Add(m_objOpt, m_objOpt, m_objOpt, m_objOpt); } //xlBook.Sheets.get_Item(lvSheetNo + 1); Microsoft.Office.Interop.Excel._Worksheet xlSheet = (Microsoft.Office.Interop.Excel._Worksheet)(xlBook.Sheets.get_Item(1)); //xlSheet.Range["A1"].Select(); xlSheet.Activate(); xlSheet.Name = GridText[lvSheetNo]; Microsoft.Office.Interop.Excel.Range m_objRange = null; m_objRange = xlSheet.get_Range("A1", m_objOpt); m_objRange = m_objRange.get_Resize(maxLineCount, columnNum); m_objRange.Value = objData; } try { xlBook.SaveCopyAs(System.Web.HttpUtility.UrlDecode(saveFileDialog1.FileName, System.Text.Encoding.UTF8)); xlBook.Saved = true; xlApp.Quit(); HelpTXD.ShowInfo("导出完成。" + saveFileDialog1.FileName); } catch //(Exception ex) { xlBook.Saved = true; xlApp.Quit(); throw; } }
private void CreateColumnFilter(DataGridViewColumn c) { if (!mAutoCreateFilters) { return; } //Raise the event about column filter creation DgvBaseColumnFilter baseColFilter = new DgvBaseColumnFilter(); switch (c.GetType().Name) { case "DataGridViewComboBoxColumn": baseColFilter = new DgvComboBoxColumnFilter(); break; case "DataGridViewCheckBoxColumn": baseColFilter = new DgvCheckBoxColumnFilter(); break; case "DataGridViewTextBoxColumn": baseColFilter = new DgvTextBoxColumnFilter(); if (_DataSourceView.Table != null && _DataSourceView.Table.Columns[c.DataPropertyName].DataType == typeof(DateTime)) { baseColFilter = new DgvDateColumnFilter(); } break; } ColumnFilterEventArgs e = new ColumnFilterEventArgs(c, baseColFilter); if (ColumnFilterAdding != null) { ColumnFilterAdding(this, e); } mColumnFilterList.Insert(c.Index, e.ColumnFilter); if (e.ColumnFilter != null)// == null when non-data column { if (ColumnFilterAdded != null) { ColumnFilterAdded(this, e); } e.ColumnFilter.Init(this, _DataSourceView, c.Index); ContextMenuStrip oMenuStrip = new ContextMenuStrip(); MyToolStripMenuItem oToolAscding, oToolDescending, oToolFilter, oToolFilterDelete; oToolAscding = new MyToolStripMenuItem("升序", ((System.Drawing.Image)(resources.GetObject("Sort_Ascending"))), new EventHandler(mMenuStripSort_Click)); oToolAscding.Name = "toolscriptmenuitemasc"; oToolAscding.DgvBaseColumn = e.ColumnFilter; oToolAscding.Size = new System.Drawing.Size(213, 22); oToolAscding.SortDirection = ListSortDirection.Ascending; oMenuStrip.Items.Add(oToolAscding); oToolDescending = new MyToolStripMenuItem("降序", ((System.Drawing.Image)(resources.GetObject("Sort_Descending"))), new EventHandler(mMenuStripSort_Click)); oToolDescending.Name = "toolscriptmenuitemdesc"; oToolDescending.DgvBaseColumn = e.ColumnFilter; oToolDescending.Size = new System.Drawing.Size(213, 22); oToolDescending.SortDirection = ListSortDirection.Descending; oMenuStrip.Items.Add(oToolDescending); oToolFilter = new MyToolStripMenuItem("过滤", ((System.Drawing.Image)(resources.GetObject("Filter_Add"))), new EventHandler(mMenuStripFilter_Click)); oToolFilter.Name = "toolscriptmenuitemFilter"; oToolFilter.DgvBaseColumn = e.ColumnFilter; oMenuStrip.Items.Add(oToolFilter); oToolFilterDelete = new MyToolStripMenuItem("取消过滤", ((System.Drawing.Image)(resources.GetObject("Filter_Delete"))), new EventHandler(mMenuStripFilterDelete_Click)); oToolFilterDelete.Name = "toolscriptmenuitemFilterDelete"; oToolFilterDelete.DgvBaseColumn = e.ColumnFilter; oMenuStrip.Items.Add(oToolFilterDelete); c.HeaderCell.ContextMenuStrip = oMenuStrip; } if (mColumnFilterList == null) { FilterHost.ComboBoxColumns.DataSource = null; return; } Dictionary <DgvBaseColumnFilter, string> dicCombox = new Dictionary <DgvBaseColumnFilter, string>(); foreach (DgvBaseColumnFilter oCol in mColumnFilterList) { dicCombox.Add(oCol, oCol.OriginalDataGridViewColumnHeaderText); } BindingSource bs = new BindingSource(); bs.DataSource = dicCombox; FilterHost.ComboBoxColumns.DataSource = bs; FilterHost.ComboBoxColumns.ValueMember = "Key"; FilterHost.ComboBoxColumns.DisplayMember = "Value"; }