В приложении, написанном на C #, для отображения некоторых данных используется Infragistics.Win.UltraWinGrid.UltraGrid. Данные в основном представляют собой набор компьютеров. Приложение может фильтровать эти компьютеры (например, «Рабочие станции», «Серверы» и т. Д.) Для просмотра. Вот как я фильтрую:
private DataView FilterTableDataForViewing(DataTable originalTable, string filterString, UltraGrid viewGrid)
{
DataView dataView = new DataView(originalTable);
dataView.RowStateFilter = DataViewRowState.CurrentRows;
dataView.RowFilter = filterString;
DataTable filteredTable = dataView.ToTable(originalTable.TableName + "_" + dataView.RowFilter);
viewGrid.DataSource = filteredTable;
gridDiscoveryMain.DisplayLayout.ViewStyleBand = ViewStyleBand.OutlookGroupBy;
SetFlagImagesAndColumnWidthsOfDiscoveryGrid();
return dataView;
}
Обратите внимание, что я установил имя таблицы для потенциально огромной строки фильтра.
Вот как я использую описанный выше метод:
string filterString = "([Build] = '4.0' AND NOT([OS Plus Version] LIKE '%Server%'))";
filterString += " OR ([Build] = '4.10')";
filterString += " OR ([Build] = '4.90')";
filterString += " OR ([Build] = '5.0' AND NOT([OS Plus Version] LIKE '%Server%'))";
filterString += " OR ([Build] = '5.1')";
filterString += " OR ([Build] = '6.0' AND ";
filterString += "(NOT([OS Plus Version] LIKE '%Server%')) OR (NOT([OS] LIKE '%Server%')))";
FilterTableDataForViewing(dataSet.Tables["DiscoveryData"], filterString, gridDiscoveryMain);
Все до этого хорошо. У UltraGrids есть средство, которое позволяет вам выбирать, какие столбцы вы хотите скрыть, и создавать новые пользовательские столбцы. При запуске этого средства запускается событие UltraGrid, называемое BeforeColumnChooserDisplayed
. Вот мой обработчик:
private void gridDiscoveryMain_BeforeColumnChooserDisplayed(object sender, BeforeColumnChooserDisplayedEventArgs e)
{
if (gridDiscoveryMain.DataSource == null)
return;
e.Cancel = true;
gridDiscoveryMain.DisplayLayout.Override.RowSelectors = DefaultableBoolean.True;
gridDiscoveryMain.DisplayLayout.Override.RowSelectorHeaderStyle = RowSelectorHeaderStyle.ColumnChooserButton;
ShowCustomColumnChooserDialog();
this.customColumnChooserDialog.CurrentBand = e.Dialog.ColumnChooserControl.CurrentBand;
this.customColumnChooserDialog.ColumnChooserControl.Style = ColumnChooserStyle.AllColumnsWithCheckBoxes;
}
А вот и реализация ShowCustomColumnChooserDialog
метода:
private void ShowCustomColumnChooserDialog()
{
DataTable originalTable = GetUnderlyingDataSource(gridDiscoveryMain);
if (this.customColumnChooserDialog == null || this.customColumnChooserDialog.IsDisposed)
{
customColumnChooserDialog = new CustomColumnChooser(ManageColumnDeleted);
customColumnChooserDialog.Owner = Parent.FindForm();
customColumnChooserDialog.Grid = gridDiscoveryMain;
}
this.customColumnChooserDialog.Show();
}
customColumnChooserDialog - это, по сути, форма, которая добавляет немного больше, чем по умолчанию в Infragistics. Самая важная вещь, о которой заботится этот код, - это метод:
private void InitializeBandsCombo( UltraGridBase grid )
{
this.ultraComboBandSelector.SetDataBinding( null, null );
if ( null == grid )
return;
// Create the data source that we can bind to UltraCombo for displaying
// list of bands. The datasource will have two columns. One that contains
// the instances of UltraGridBand and the other that contains the text
// representation of the bands.
UltraDataSource bandsUDS = new UltraDataSource( );
bandsUDS.Band.Columns.Add( "Band", typeof( UltraGridBand ) );
bandsUDS.Band.Columns.Add( "DisplayText", typeof( string ) );
foreach ( UltraGridBand band in grid.DisplayLayout.Bands )
{
if ( ! this.IsBandExcluded( band ) )
{
bandsUDS.Rows.Add( new object[] { band, band.Header.Caption } );
}
}
this.ultraComboBandSelector.DisplayMember = "DisplayText";
this.ultraComboBandSelector.ValueMember= "Band";
this.ultraComboBandSelector.SetDataBinding( bandsUDS, null );
// Hide the Band column.
this.ultraComboBandSelector.DisplayLayout.Bands[0].Columns["Band"].Hidden = true;
// Hide the column headers.
this.ultraComboBandSelector.DisplayLayout.Bands[0].ColHeadersVisible = false;
// Set some properties to improve the look & feel of the ultra combo.
this.ultraComboBandSelector.DropDownWidth = 0;
this.ultraComboBandSelector.DisplayLayout.Override.HotTrackRowAppearance.BackColor = Color.LightYellow;
this.ultraComboBandSelector.DisplayLayout.AutoFitStyle = AutoFitStyle.ResizeAllColumns;
this.ultraComboBandSelector.DisplayLayout.BorderStyle = UIElementBorderStyle.Solid;
this.ultraComboBandSelector.DisplayLayout.Appearance.BorderColor = SystemColors.Highlight;
}
Если я прошагаю по коду, все будет круто, пока я не выйду из обработчика событий (точка, в которой элемент управления возвращается в форму). Я получаю исключение ArgumentException только , когда пытаюсь показать диалоговое окно CustomColumnChooser из сетки, в которой отображаются отфильтрованные данные . Не тот, который показывает строку с ошибкой в вашем коде, а тип, который вызывает окно сообщения об ошибке «Microsoft .NET Framework», в котором говорится «Необработанное исключение произошло в вашем приложении ...». Это означает, что я не могу проследить, что это вызывает. После этого приложение не развалится, но в будущем появится диалоговое окно CustomColumnChooser с контейнером, в котором нет ничего, кроме белого фона и большой красной буквы "X".
И трассировка стека:
See the end of this message for details on invoking
just-in-time (JIT) debugging instead of this dialog box.
************** Exception Text **************
System.ArgumentException: Child list for field DiscoveryData_([Build] = '4 cannot be created.
at System.Windows.Forms.BindingContext.EnsureListManager(Object dataSource, String dataMember)
at System.Windows.Forms.BindingContext.EnsureListManager(Object dataSource, String dataMember)
at System.Windows.Forms.BindingContext.EnsureListManager(Object dataSource, String dataMember)
at System.Windows.Forms.BindingContext.EnsureListManager(Object dataSource, String dataMember)
at System.Windows.Forms.BindingContext.EnsureListManager(Object dataSource, String dataMember)
at System.Windows.Forms.BindingContext.EnsureListManager(Object dataSource, String dataMember)
at System.Windows.Forms.BindingContext.EnsureListManager(Object dataSource, String dataMember)
at System.Windows.Forms.BindingContext.get_Item(Object dataSource, String dataMember)
at Infragistics.Win.UltraWinGrid.UltraGridLayout.ListManagerUpdated(BindingManagerBase bindingManager)
at Infragistics.Win.UltraWinGrid.UltraGridLayout.ListManagerUpdated()
at Infragistics.Win.UltraWinGrid.UltraGridBase.Set_ListManager(Object newDataSource, String newDataMember)
at Infragistics.Win.UltraWinGrid.UltraGridBase.SetDataBindingHelper(Object dataSource, String dataMember, Boolean hideNewColumns, Boolean hideNewBands)
at Infragistics.Win.UltraWinGrid.UltraGridBase.SetDataBinding(Object dataSource, String dataMember, Boolean hideNewColumns, Boolean hideNewBands)
at Infragistics.Win.UltraWinGrid.UltraGridBase.SetDataBinding(Object dataSource, String dataMember, Boolean hideNewColumns)
at Infragistics.Win.UltraWinGrid.UltraGridBase.SetDataBinding(Object dataSource, String dataMember)
at Infragistics.Win.UltraWinGrid.UltraGridColumnChooser.CreateColumnChooserGridDataStructure()
at Infragistics.Win.UltraWinGrid.UltraGridColumnChooser.Initialize()
at Infragistics.Win.UltraWinGrid.UltraGridColumnChooser.VerifyInitialized()
at Infragistics.Win.UltraWinGrid.ColumnChooserGridCreationFilter.BeforeCreateChildElements(UIElement parent)
at Infragistics.Win.UIElement.VerifyChildElements(ControlUIElementBase controlElement, Boolean recursive)
at Infragistics.Win.UltraWinGrid.UltraGridUIElement.VerifyChildElements(ControlUIElementBase controlElement, Boolean recursive)
at Infragistics.Win.UIElement.VerifyChildElements(Boolean recursive)
at Infragistics.Win.UltraWinGrid.UltraGridUIElement.InternalInitializeRect(Boolean verify)
at Infragistics.Win.UltraWinGrid.UltraGridLayout.GetUIElement(Boolean verify, Boolean forceInitializeRect)
at Infragistics.Win.UltraWinGrid.UltraGrid.OnPaint(PaintEventArgs pe)
at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer, Boolean disposeEventArgs)
at System.Windows.Forms.Control.WmPaint(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
Дочерний список для поля DiscoveryData ([Build] = '4 не может быть создан не очень полезен. Что это действительно означает?