public FormAccountList() { InitializeComponent(); dataSet1 = ArxDs.ds; accountsBindingSource.DataSource = ArxDs.ds; dataGridView1.DataSource = accountsBindingSource; using (var remainingColumn = new DataGridViewTextBoxColumn { Width = 100, HeaderText = "Текущее состояние", ReadOnly = true }) { dataGridView1.Columns.Add(remainingColumn); } var view1 = new DataView(ArxDs.ds.Tables["Accounts"], "", "", DataViewRowState.CurrentRows); if (!view1.Cast <DataRowView>() .Any(rv => rv.Row.Field <string>("Account") == "Основной")) { DataRowView newRow = view1.AddNew(); newRow["Account"] = "Основной"; newRow["StartSum"] = 0; newRow.EndEdit(); } }
static public void SaveRemarks(string ownerGUIDFieldName, string ownerGUID, string userMessagePrefix, DataView v) { if (v == null) { return; } string savefilter = v.RowFilter; v.RowFilter = ""; // ReSharper disable InconsistentNaming using (var Remark_u = new iTRAACProc("Remark_u")) // ReSharper restore InconsistentNaming foreach (var remark in v.Cast <DataRowView>().Where(remark => remark.IsDirty())) { Remark_u.AssignValues(remark); if (!Remark_u.ExecuteNonQuery(userMessagePrefix + " Save Remark: ")) { continue; } remark["RowGUID"] = Remark_u["@RowGUID"]; //for inserts remark.AcceptChanges(); } v.RowFilter = savefilter; }
public static string ToStringTableString(this DataView dataView) { Assert.IsNotNull(dataView, nameof(dataView)); var rows = dataView.Cast <DataRowView>().Select((dataRowView, rowIndex) => dataRowView.Row); var columns = dataView.Table.Columns.Cast <DataColumn>().Select(DataTableExtensions.ToStringTableColumnInfo).ToArray(); return(rows.ToString(columns)); }
private static IEnumerable <string> GetIndexNames(DataView indexes) { var list = new List <string>(); foreach (var indexName in indexes.Cast <DataRowView>().Select(row => row["INDEX_NAME"].ToString()).Where(indexName => !list.Contains(indexName))) { list.Add(indexName); } return(list.OrderBy(n => n)); }
private static void checkColumnVisibility(this DataView view, string columnName, Func <object, bool> cellValueCheckerFunc) { if (!view.Table.Columns.Contains(columnName)) { return; } var columnHidden = view.Cast <DataRowView>().All(row => cellValueCheckerFunc(row[columnName])); view.Table.Columns[columnName].SetHidden(columnHidden); }
private Dictionary <int, int> ColumnsToSum(DataView data, IEnumerable <int> indexes) { var sumByIndex = from row in data.Cast <DataRowView>() from index in indexes group row by index into g select new { Index = g.Key, Sum = g.Sum(r => (int)r[g.Key]) }; return(sumByIndex.ToDictionary(a => a.Index, a => a.Sum)); }
/// <summary> /// Denies all buddy requests for the current user. /// </summary> public void DenyAllRequests() { DataTable dt = this.All(); DataView dv = dt.DefaultView; dv.RowFilter = "Approved = 0 AND UserID = {0}".FormatWith(YafContext.Current.PageUserID); foreach ( DataRowView drv in dv.Cast<DataRowView>() .Where(drv => Convert.ToDateTime(drv["Requested"]).AddDays(14) < DateTime.UtcNow)) { this.DenyRequest((int)drv["FromUserID"]); } }
/// <summary> /// Removes from the DataView all users but guests. /// </summary> /// <param name="activeUsers"> /// The active users. /// </param> private void RemoveAllButGusts([NotNull] ref DataView activeUsers) { if (activeUsers.Count <= 0) { return; } // remove non-guest users... foreach (DataRowView row in activeUsers.Cast <DataRowView>().Where(row => !Convert.ToBoolean(row["IsGuest"]))) { // remove this active user... row.Delete(); } }
private void UseSoredDataViews() { if (_viewCol1Asc == null) { _viewCol1Asc = new DataView(_table, null, "Col1 ASC", DataViewRowState.Unchanged); _viewCol2Desc = new DataView(_table, null, "Col2 DESC", DataViewRowState.Unchanged); } var rows = _viewCol1Asc.Cast <DataRowView>().Take(_countToTake).Select(vr => (MyRow)vr.Row); IterateRows(rows); rows = _viewCol2Desc.Cast <DataRowView>().Take(_countToTake).Select(vr => (MyRow)vr.Row); IterateRows(rows); }
private int getPercentageMax(DataView dataView, string columnName) { try { var allValues = dataView.Cast <DataRowView>() .Select(row => row[columnName]) .Where(x => x != null && x != DBNull.Value) .Select(x => x.ConvertedTo <double>()); return(Convert.ToInt32(allValues.Max())); } catch (Exception) { return(100); } }
/// <summary> /// 检查是否选择了任何一条记录 /// </summary> /// <param name="dataView">目标表</param> /// <param name="fieldSelected">当前被选中的字段</param> /// <returns>是否有选中的记录</returns> public static bool CheckInputSelectAnyOne(DataView dataView, string fieldSelected) { bool returnValue = dataView.Cast <DataRowView>().Any(dataRowView => dataRowView.Row[fieldSelected].ToString().ToUpper().Equals(true.ToString().ToUpper())); //V2.5版本 //foreach (DataRowView dataRowView in dataView) //{ // if (!dataRowView.Row[fieldSelected].ToString().ToUpper().Equals(true.ToString().ToUpper())) continue; // returnValue = true; // break; //} if (!returnValue) { MessageBoxHelper.ShowWarningMsg(RDIFrameworkMessage.MSGC023); } return(returnValue); }
private void ListChanged(object sender, ListChangedEventArgs e) { switch (e.ListChangedType) { case ListChangedType.ItemAdded: var newRow = (_dataView[e.NewIndex] as DataRowView).Row as TDataRow; _collection.Insert(e.NewIndex, newRow); CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, newRow, e.NewIndex)); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Count))); break; case ListChangedType.ItemDeleted: var oldRow = _collection[e.NewIndex]; _collection.RemoveAt(e.NewIndex); CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, oldRow, e.NewIndex)); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Count))); break; case ListChangedType.ItemMoved: var row = _collection[e.OldIndex]; _collection.RemoveAt(e.OldIndex); _collection.Insert(e.NewIndex, row); CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Move, row, e.NewIndex, e.OldIndex)); break; case ListChangedType.Reset: var count = _collection.Count; _collection.Clear(); foreach (var item in _dataView.Cast <DataRowView>().Select(view => view.Row as TDataRow)) { _collection.Add(item); } CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); if (_collection.Count == count) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Count))); } break; } }
public IEnumerable <KeyValuePair <string, CryptoKey> > GetKeys(string bucket) { // properly escape the URL to prevent injection attacks. string value = bucket.Replace("'", "''"); string filter = string.Format( CultureInfo.InvariantCulture, "{0} = '{1}'", dataSet.CryptoKey.BucketColumn.ColumnName, value); string sort = dataSet.CryptoKey.ExpiresUtcColumn.ColumnName + " DESC"; DataView view = new DataView(dataSet.CryptoKey, filter, sort, DataViewRowState.CurrentRows); if (view.Count == 0) { yield break; } foreach (CustomStoreDataSet.CryptoKeyRow row in view.Cast <DataRowView>().Select(rv => rv.Row)) { yield return(new KeyValuePair <string, CryptoKey>(row.Handle, new CryptoKey(row.Secret, row.ExpiresUtc))); } }
private void fillComboBoxes() { var view1 = new DataView(ArxDs.ds.Tables["Accounts"], "", "", DataViewRowState.CurrentRows); var view2 = new DataView(ArxDs.ds.Tables["Accounts"], "", "", DataViewRowState.CurrentRows); if (view1.Cast <DataRowView>().All(rv => rv.Row.Field <string>("Account") != "Основной")) { var newRow = view1.AddNew(); newRow["Account"] = "Основной"; newRow["StartSum"] = 0; newRow.EndEdit(); } comboBox1.DataSource = view1; comboBox1.DisplayMember = "Account"; comboBox2.DataSource = view2; comboBox2.DisplayMember = "Account"; }
protected void BindBasket() { var sql = "SELECT id, Name, Price FROM tblImages WHERE id IN ({0})"; var values = (List<string>)Session["Cart"]; if (values.Count > 0) { var parms = values.Select((s, i) => "@p" + i.ToString()).ToArray(); var inclause = string.Join(",", parms); BasketData.SelectCommand = string.Format(sql, inclause); BasketData.SelectParameters.Clear(); for (var i = 0; i < parms.Length; i++) { BasketData.SelectParameters.Add(parms[i].Replace("@", ""), values[i]); } DataView view = (DataView)BasketData.Select(DataSourceSelectArguments.Empty); var costQuery = view.Cast<DataRowView>().Select(drv => drv.Row.Field<int>("Price")); cost = costQuery.Sum(); Basket.DataSource = view; Basket.DataBind(); } }
/// <summary> /// </summary> /// <param name="v"></param> /// <param name="respectRowFilter">If true, does NOT clear RowFilter prior to dirty check.</param> /// <returns></returns> public static bool IsDirty(this DataView v, bool respectRowFilter = true) { if (v == null) { return(false); } //nugget: this approach of clearing the rowfilter, and then restoring it created a buggy. // TextBox bound to this view would lose it's focus as you were entering text, not gonna work. // the entry would fire the PropertyChanged -> IsModified -> IsDirty() // // but the typical save logic really needs a way to know *everything* that should be saved, including Filtered rows // so unfortunately this is a sharp edge that we have to keep around... // namely, IsDirty() calls has been removed from the IsModified logic, IsModified is now a simple get/set property // and IsDirty() should only be called for saves where the user has already changed focus to a Save button anyway //Debug.Assert(v.RowFilter == "" || RespectRowFilter == true, "Checking dirty on a DataView with a RowFilter is debatable"); var saveFilter = ""; try { if (!respectRowFilter & v.RowFilter != "") { saveFilter = v.RowFilter; v.RowFilter = ""; } return(v.Cast <DataRowView>().Any(r => r.IsDirty())); } finally { if (saveFilter != "") { v.RowFilter = saveFilter; } } }
public static IEnumerable <string> SaveCSVFiles(string savePath, string fileName, DataView data, bool includeHeaderRow = true, TableDefinition tableDefinition = null, IEnumerable <string> additionalHeaderRows = null) { if (string.IsNullOrEmpty(savePath)) { throw new ArgumentException(typeof(CSVExportHelper).Name + ":" + System.Reflection.MethodBase.GetCurrentMethod().Name + " - Path is required"); } if (string.IsNullOrEmpty(fileName)) { throw new ArgumentException(typeof(CSVExportHelper).Name + ":" + System.Reflection.MethodBase.GetCurrentMethod().Name + " - Filename is required"); } List <string> savedFileNames = new List <string>(); if (data != null && data.Count > 0) { if (!savePath.EndsWith(Path.DirectorySeparatorChar.ToString())) { savePath += Path.DirectorySeparatorChar; } List <string> rows = new List <string>(); string headerRow = null; if (includeHeaderRow) { if (tableDefinition != null) { List <string> headerList = new List <string>(); foreach (DataColumn col in data.Table.Columns) { ColumnDefinition foundDef = tableDefinition.Columns.Where(x => x.Name.Equals(col.ColumnName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault(); headerList.Add((foundDef != null) ? foundDef.DisplayName : col.ColumnName); } headerRow = string.Join(",", headerList); } else { headerRow = data.Table.ConvertHeaderRowToCSV(); } } foreach (DataRowView row in data.Cast <DataRowView>()) { rows.Add(row.ConvertToCSV()); } if (rows != null && rows.Any(x => !string.IsNullOrEmpty(x))) { bool multipleFiles = false; if (rows.Count() > DEFAULT_ROWLIMIT) { multipleFiles = true; } string filenameNoExt = fileName.Replace(EXTENSION, ""); StringBuilder sb = new StringBuilder(); int rowCount = 0; int fileCount = 1; string generatedFileName = string.Empty; if (!Directory.Exists(savePath)) { Directory.CreateDirectory(savePath); } if (additionalHeaderRows != null && additionalHeaderRows.Any()) { foreach (string additionalHeaderRow in additionalHeaderRows) { sb.AppendLine(additionalHeaderRow); } } if (includeHeaderRow && !string.IsNullOrEmpty(headerRow)) { sb.AppendLine(headerRow); } foreach (string row in rows.Where(x => !string.IsNullOrEmpty(x))) { sb.AppendLine(row); rowCount++; if (rowCount == DEFAULT_ROWLIMIT) { generatedFileName = savePath + filenameNoExt + "_" + fileCount.ToString() + EXTENSION; File.WriteAllText(generatedFileName, sb.ToString()); savedFileNames.Add(generatedFileName); sb = new StringBuilder(); if (includeHeaderRow && !string.IsNullOrEmpty(headerRow)) { sb.AppendLine(headerRow); } fileCount++; rowCount = 0; } } if (rowCount > 0) { generatedFileName = savePath + filenameNoExt + (multipleFiles ? "_" + fileCount.ToString() : "") + EXTENSION; File.WriteAllText(generatedFileName, sb.ToString()); savedFileNames.Add(generatedFileName); } } } return(savedFileNames); }
public static IReadOnlyList <T> AllValuesInColumn <T>(this DataView dataView, string columnName) { return(dataView.Cast <DataRowView>().Select(row => row[columnName].ConvertedTo <T>()).ToList()); }
public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { var service = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService)); if (service == null) { return(value); } var column = TwoDARowTypeDescriptor.GetColumn(context); var schemaColumn = TwoDARowTypeDescriptor.GetSchemaColumn(context); if (column == null || schemaColumn == null || schemaColumn.RowSource == null) { return(value); } var refDoc = (TwoDADocument)column.Table.ExtendedProperties[typeof(TwoDADocument)]; var srcDoc = MainWindow.Instance.GetReferencedTwoDADocument(refDoc, schemaColumn.RowSource); if (srcDoc == null) { string text = string.Format( "RowRef lookup is currently disabled for this property, because '{0}' is not opened.", schemaColumn.RowSource); MessageBox.Show(text, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return(value); } if (!srcDoc.Data.Columns.Contains(schemaColumn.RowSourceKeyField)) { return(value); } var keyColumn = srcDoc.Data.Columns[schemaColumn.RowSourceKeyField]; object result = value; var view = new DataView(srcDoc.Data); var selectedRowView = (from rowView in view.Cast <DataRowView>() where object.Equals(rowView.Row[keyColumn], value) select rowView ).FirstOrDefault(); var panel = new Panel { Width = 350, Height = 300 }; var searchTextBox = new TextBox { Dock = DockStyle.Top }; var bindingSource = new BindingSource { DataSource = view }; var grid = new DataGridView { AutoGenerateColumns = false, BorderStyle = BorderStyle.None, Dock = DockStyle.Fill, ColumnHeadersVisible = false, RowHeadersVisible = false, SelectionMode = DataGridViewSelectionMode.FullRowSelect, MultiSelect = false, ReadOnly = true, ScrollBars = ScrollBars.Vertical, AllowUserToResizeColumns = false, AllowUserToResizeRows = false, AllowUserToAddRows = false, AllowUserToDeleteRows = false, DataSource = bindingSource }; var timer = new Timer { Interval = 800 }; grid.Columns.AddRange( new[] { new DataGridViewTextBoxColumn { DataPropertyName = keyColumn.ColumnName, AutoSizeMode = DataGridViewAutoSizeColumnMode.None, Width = 75, DefaultCellStyle = { WrapMode = DataGridViewTriState.True } }, new DataGridViewTextBoxColumn { DataPropertyName = srcDoc.Data.Columns[1].ColumnName, AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill } }); panel.Controls.Add(grid); panel.Controls.Add(searchTextBox); searchTextBox.TextChanged += delegate { timer.Stop(); timer.Start(); }; timer.Tick += delegate { timer.Stop(); var oldCursor = grid.Cursor; panel.Cursor = Cursors.AppStarting; if (string.IsNullOrEmpty(searchTextBox.Text)) { view.RowFilter = null; } else { var pattern = new StringBuilder(); foreach (char c in searchTextBox.Text) { switch (c) { case '\'': pattern.Append(c); pattern.Append(c); break; case '*': case '%': case '[': case ']': pattern.Append('['); pattern.Append(c); pattern.Append(']'); break; default: pattern.Append(c); break; } view.RowFilter = string.Format( "[{0}] LIKE '*{1}*'", srcDoc.Data.Columns[1].ColumnName, pattern); } } panel.Cursor = oldCursor; }; bindingSource.CurrentChanged += delegate { selectedRowView = (DataRowView)bindingSource.Current; }; grid.CellDoubleClick += delegate { result = selectedRowView != null ? selectedRowView.Row[keyColumn] : value; service.CloseDropDown(); }; grid.KeyDown += delegate(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { result = selectedRowView != null ? selectedRowView.Row[keyColumn] : value; service.CloseDropDown(); e.Handled = true; } }; grid.KeyPress += delegate(object sender, KeyPressEventArgs e) { if (!char.IsControl(e.KeyChar)) { searchTextBox.Focus(); searchTextBox.SelectAll(); SendKeys.Send(e.KeyChar.ToString()); } }; grid.DataBindingComplete += delegate { var selectedIndex = bindingSource.IndexOf(selectedRowView); if (selectedIndex >= 0) { grid.FirstDisplayedScrollingRowIndex = selectedIndex; grid.CurrentCell = grid.Rows[selectedIndex].Cells[0]; } }; panel.GotFocus += delegate { grid.Focus(); }; bindingSource.DataSource = view; service.DropDownControl(panel); return(result ?? (object)DBNull.Value); }
public static IEnumerable <TRow> Rows <TRow>(this DataView view) where TRow : DataRow { return(view.Cast <DataRowView>().Select(drv => (TRow)drv.Row)); }
///<summary>Gets the DataRows in a DataView.</summary> public static IEnumerable <DataRow> Rows(this DataView view) { return(view.Cast <DataRowView>().Select(drv => drv.Row)); }
public static void New(int ZColumns, ref DataView view, String fieldX, String fieldY, ref DataGridView dgv) { Clean(ref dgv); if (view.Count != 0) { dgv.Tag = view; int num = 1; while (num <= ZColumns) { dgv.Columns.Add(string.Empty, string.Empty); num++; } dgv.Columns.Add(fieldY, fieldY); IEnumerable <DataRowView> enumerable = view.Cast <DataRowView>().ToList(); IList <object> list = Dumb.Hash.HashFrom <object>(enumerable, fieldX); foreach (object xi in list) { dgv.Columns.Add(xi.ToString(), xi.ToString()); } IList <object> list2 = Dumb.Hash.HashFrom <object>(enumerable, fieldY); int w = 0; foreach (object yi in list2) { w = dgv.Rows.Add(); IEnumerable <DataRowView> Y = enumerable.Where(i => i.Row.Field <object>(fieldY).Equals(yi)); foreach (object xi in list) { DataGridViewCell cell1 = dgv[xi.ToString(), w]; IEnumerable <DataRowView> X = Y.Where(i => i.Row.Field <object>(fieldX).Equals(xi)); foreach (DataRowView rowV in X) { DataRow row = rowV.Row; if (cell1.Tag == null) { cell1.ErrorText = null; row.RowError = null; cell1.Tag = row; dgv[fieldY, w].Tag = row; for (num = 0; num <= ZColumns; num++) { dgv[num, w].Tag = row; } dgv[fieldY, w].Value = yi; } else { DataRow tag = (DataRow)cell1.Tag; cell1.ErrorText += "Duplicated by Row: " + row.Table.Rows.IndexOf(row).ToString() + "\n"; tag.RowError += cell1.ErrorText + "\n"; row.RowError += "Duplicating Row: " + tag.Table.Rows.IndexOf(tag).ToString() + "\n"; } } } } list.Clear(); list2.Clear(); } }
private void IdentifyNextMediaSubset_Click(object sender, RoutedEventArgs e) { using (WaitCursorWrapper w = new WaitCursorWrapper()) //using (DataView files = new DataView(WorkingFilesTable)) { if (gridIncrementalHistory.Items.Count == 0) { MessageBox.Show("Press [New Incremental Backup] button -OR-\r\nRight mouse the Incremental Backup History grid\r\nto establish the container for these new files", "No Incremental Backup Container has been established", MessageBoxButton.OK, MessageBoxImage.Information); return; } FileSystemNode.GetSelected(SelectedFoldersTable, IncludedFilesTable); using (Proc Files_UploadCompare = new Proc("Files_UploadCompare")) { Files_UploadCompare["@BackupProfileID"] = (int)cbxBackupProfiles.SelectedValue; Files_UploadCompare["@AllFiles"] = IncludedFilesTable; // <= ****** WorkingFilesTable = Files_UploadCompare.ExecuteDataTable(); lblCurrentDisc.Content = Files_UploadCompare["@NextDiscNumber"].ToString(); } DataView files = WorkingFilesTable.DefaultView; gridFilesWorkingSet.ItemsSource = files; chkShowErrorsOnly.IsChecked = false; WorkingFilesTable.DefaultView.RowFilter = ""; files.Sort = DefaultSort; long maxbytes = (long)((decimal)((DataRowView)cbxMediaSize.SelectedItem)["SizeGB"] * 1024 * 1024 * 1024); long remainingbytes = files.Cast <DataRowView>().Select(drv => (long)drv["Size"]).Sum(); lblTotalBytes.Text = remainingbytes.ToString(BigNumberStringFormat); //nugget: requires System.Data.DataSetExtensions assembly added to project References lblTotalFiles.Text = files.Count.ToString(BigNumberStringFormat); long remainder = 0; long DiscCount = Math.DivRem(remainingbytes, maxbytes, out remainder); lblDiscCount.Text = String.Format("{0} Full + {1:#.###} GB leftover", DiscCount, remainder / 1024 / 1024 / 1024); int retrycount = 10; long bytecount = 0; long recordcount = 0; long errorcount = 0; int recordindex = 0; //we need to know this loopcount outside the loop at the end in order to scroll to this current location in the grid for (recordindex = 0; recordindex < files.Count; recordindex++) { //DataGridRow gridrow = WPFHelpers.GetDataGridRow(gridFilesWorkingSet, recordindex); long nextsize = Convert.ToInt64(files[recordindex]["Size"]); if (bytecount + nextsize > maxbytes) { //initially assume we just ran into too big of a file to pack on near the end of our free space... //so for a few times, try to find another slightly smaller file... if (--retrycount > 0) { continue; } //and after those retries are exhausted, we've successully crammed as close to 100% full as we can at that point break; } retrycount = 10; //when we successfully squeeze on another file, reset the retry count if (CheckFileLocked(files[recordindex]["FullPath"].ToString())) { files[recordindex]["Selected"] = true; bytecount += nextsize; } else { files[recordindex]["SkipError"] = true; errorcount++; } } lblQtySelected.Text = recordcount.ToString(BigNumberStringFormat); lblBytesSelected.Text = bytecount.ToString(BigNumberStringFormat); lblErrorCount.Text = errorcount.ToString(BigNumberStringFormat); gridFilesWorkingSet.ScrollIntoView(gridFilesWorkingSet.Items[recordindex - 1]); } }
/// <summary> /// the best method so far... Linq /// </summary> /// <param name="view"></param> /// <param name="fieldX"></param> /// <param name="Zfields"></param> /// <param name="dgv"></param> public static void New(ref DataView view, String fieldX, String fieldXSort, String[] Zfields, ref DataGridView dgv, int MinGreen) { Clean(ref dgv); int maxVal = 0xff; if (view.Count == 0) { return; } dgv.Tag = view; dgv.ReadOnly = true; dgv.Cursor = Cursors.Hand; dgv.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText; dgv.AllowUserToAddRows = false; dgv.AllowUserToDeleteRows = false; dgv.AllowUserToOrderColumns = true; foreach (string AZfield in Zfields) { if (!dgv.Columns.Contains(AZfield)) { dgv.Columns.Add(AZfield, AZfield); } } Func <DataRowView, string> keySel = o => { string keyLong = string.Empty; foreach (string AZfield in Zfields) { keyLong += o[AZfield]; } return(keyLong); }; IEnumerable <DataRowView> enumerable = view.Cast <DataRowView>().ToList(); IEnumerable <IGrouping <string, DataRowView> > EnergyGroup = enumerable.GroupBy(keySel).ToList(); Random random = new Random(); int red = 0; int blue = 0; HashSet <object> set = new HashSet <object>(); int w = 0; foreach (IGrouping <string, DataRowView> i in EnergyGroup) { IEnumerable <DataRow> rows = i.Select(o => o.Row).ToList(); w = dgv.Rows.Add(); if (set.Add(i.Key)) { red = random.Next(MinGreen, maxVal); blue = random.Next(MinGreen, maxVal); } for (int a = 0; a < Zfields.Count(); a++) { string AZfield = Zfields[a]; object key = rows.First()[AZfield]; dgv[AZfield, w].Value = key; dgv[AZfield, w].Tag = rows; dgv[AZfield, w].Style.BackColor = Color.FromArgb(red, MinGreen, blue); dgv[AZfield, w].Style.ForeColor = Color.White; } //fill rows with x columns if (string.IsNullOrEmpty(fieldXSort)) { rows = rows.OrderByDescending(o => o.Field <double>(fieldXSort)); } foreach (DataRow r in rows) { string x = r[fieldX].ToString().ToUpper(); if (!dgv.Columns.Contains(x)) { dgv.Columns.Add(x, x); } DataGridViewCell cell1 = dgv[x, w]; if (cell1.Tag == null) { cell1.ErrorText = string.Empty; r.RowError = string.Empty; cell1.Tag = r; } else { DataRow tag = (DataRow)cell1.Tag; cell1.ErrorText += "Duplicated by Row: " + r.Table.Rows.IndexOf(r).ToString() + "\n"; tag.RowError += cell1.ErrorText + "\n"; r.RowError += "Duplicating Row: " + tag.Table.Rows.IndexOf(tag).ToString() + "\n"; } } } }
public static IDictionary <int, int> GetRandomizeTrialBucket(int protocolId) { Dictionary <int, int> _bucket = new Dictionary <int, int>(); var protocolConfiguration = GetProtocolConfigurationNode(); if (protocolConfiguration != null) { // get protocol details DataView protocolView = BusinessObject.GetByFieldsAsDataView <Protocol>(new Dictionary <string, object> { { Protocol.ProtocolId, protocolId } }); // get schemas DataView schemas = ProtocolMgmtDa.GetSchemasByProtocol(protocolId).DefaultView; schemas.Sort = ProtocolSchema.ProtocolSchemaId + " ASC"; // read config var xDoc = XmlUtil.GetModulesConfigXml(); // get a list of protocols to match and weights var protocolMatchNodes = xDoc.SelectNodes("//module[@name='Protocol Management']//randomization//protocol"); var protocolMatches = from node in protocolMatchNodes.Cast <XmlNode>() let matchProtocol = node.Attributes["matchProtocol"].Value let matchVersion = node.Attributes["matchVersion"] != null ? node.Attributes["matchVersion"].Value : "" let schemasNodes = node.SelectNodes("//schema").Cast <XmlNode>() where schemasNodes.Count() > 0 select new { MatchProtocol = matchProtocol, MatchVersion = matchVersion, Weights = from s in schemasNodes select new { SchemaName = s.Attributes["name"].Value, Weight = int.Parse(s.Attributes["weight"].Value) } }; // find match // default weights (1) _bucket = new Dictionary <int, int>(); foreach (var protocolMatch in protocolMatches) { // match Protocol (required) protocolView.RowFilter = protocolMatch.MatchProtocol; if (protocolView.Count > 0) { // match Version (optional) schemas.RowFilter = !string.IsNullOrEmpty(protocolMatch.MatchVersion) ? protocolMatch.MatchVersion : string.Empty; if (schemas.Count > 0) { var schemaAndIds = from row in schemas.Cast <DataRowView>() select new { SchemaId = (int)row[ProtocolSchema.ProtocolSchemaId], SchemaName = row[ProtocolSchema.ProtocolArmDescription].ToString() }; var match = from schema in schemaAndIds join w in protocolMatch.Weights on schema.SchemaName equals w.SchemaName select new { SchemaId = schema.SchemaId, Weight = w.Weight }; // set weights if (match.Count() > 0) { foreach (var m in match) { _bucket.Add(m.SchemaId, m.Weight); } // end config search break; } } } } /* * // build bucket of schema -> weight: !important: fill bucket only within valid indexes * int length = Math.Min(schemas.Count, _weights.Length); * for (int i = 0; i < length; i++) * { * int schemaId = (int)schemas[i][ProtocolSchema.ProtocolSchemaId]; * int weight = _weights[i]; * /* * // normalize max accrued schemas = 0 weight * schemas.RowFilter = ProtocolSchema.ProtocolSchemaId + " = " + schemaId + " AND IsMaxAccrual > 0"; * if (schemas.Count > 0) * { * weight = 0; * } * * // !import: reset filter * schemas.RowFilter = string.Empty; * _bucket.Add(schemaId, weight); * } */ // DEFAULT (1): if (_bucket.Count == 0) { schemas.RowFilter = string.Empty; _bucket = schemas.Cast <DataRowView>().ToDictionary(row => (int)row[ProtocolSchema.ProtocolSchemaId], row => 1); } } // return bucket return(_bucket); }