Tell me what could be the problem? The task is as follows: all data must be removed from the cube, and by clicking on the checkbox of a certain dimension, it should be displayed in the DataGrid
enter image description here

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using Microsoft.AnalysisServices.AdomdClient; using System.Data; namespace WpfApplication1 { /// <summary> /// Логика взаимодействия для MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); GetDimensions(); listBox.UpdateLayout(); } public bool IsChecked { get; set; } private void GetDimensions() { // prepare adomd connection using (AdomdConnection mdConn = new AdomdConnection()) { mdConn.ConnectionString = "Data Source=Сергей;Initial Catalog=MultidimensionalProject1"; mdConn.Open(); // перебор кубов foreach (CubeDef cube in mdConn.Cubes) { if (cube.Type != CubeType.Cube) continue; // перебор измерений foreach (Dimension dimension in cube.Dimensions) { // перебор иерархий foreach (Hierarchy hierarchy in dimension.Hierarchies) { if (!hierarchy.Name.Contains("Id") && !hierarchy.Name.Contains("Measures")) listBox.Items.Add(hierarchy.UniqueName + ".[" + hierarchy.Name + "]"); } } } } } private void BuildQuery() { } private void UpdateChart(string mdxQuery) { // prepare adomd connection using (AdomdConnection mdConn = new AdomdConnection()) { mdConn.ConnectionString = "Data Source=Сергей;Initial Catalog=MultidimensionalProject1"; mdConn.Open(); AdomdCommand mdCommand = mdConn.CreateCommand(); mdCommand.CommandText = mdxQuery; // << MDX Query // выполняем запрос, получаем CellSet CellSet cs; cs = mdCommand.ExecuteCellSet(); // our method supports only 2-Axes CellSets if (cs.Axes.Count != 2) return; TupleCollection tuplesOnColumns = cs.Axes[0].Set.Tuples; TupleCollection tuplesOnRows = cs.Axes[1].Set.Tuples; // 2 дублирующиеся структуры данных для графиков и таблицы с данными var Data = new DataTable(); if (tuplesOnColumns.Count > 0 && tuplesOnRows.Count > 0) { // Создаем заголовки в таблице на основе названий for (int m = 0; m < tuplesOnRows[0].Members.Count; m++) { Data.Columns.Add(tuplesOnRows[0].Members[m].ParentLevel.Name); } Data.Columns.Add(tuplesOnColumns[0].Members[0].Caption); // Выводим строки с данными for (int row = 0; row < tuplesOnRows.Count; row++) { int m = 0; // объект - для занесения в таблицу данных var o = new object[tuplesOnRows[row].Members.Count + tuplesOnColumns.Count]; for (; m < tuplesOnRows[row].Members.Count; m++) { // заносим названия измерений для таблицы (по колонкам) o[m] = tuplesOnRows[row].Members[m].Caption; } // заносим непосредственно значения метрики (кол-во обращений) в последнюю колонку строки (для таблицы) for (int col = 0; col < tuplesOnColumns.Count; col++) { o[m + col] = (cs.Cells[col, row].Value.ToString()); } //добавляем строку таблицы Data.Rows.Add(o); } } // обновляем визуализацию данных try { dataGrid.ItemsSource = Data.DefaultView; dataGrid.Items.Refresh(); } catch { } } } private void CheckBox_Click(object sender, RoutedEventArgs e) { var cb = sender as CheckBox; var item = cb.DataContext; listBox.SelectedItem = item; // выход, если задан пустой запрос if (listBox.SelectedItems.Count == 0) return; // проверяем, установлен ли фильтр по кол-ву обращений bool filter = cbFilter.IsChecked == true && txtFilterValue.Text != "" && Convert.ToInt32(txtFilterValue.Text) >= 0; // первая часть запроса: количсество обращений string query = "SELECT NON EMPTY { [Measures].[Hits Count] } ON COLUMNS, NON EMPTY {"; // если установлен фильтр - добавляем его query += filter ? "filter ( {" : ""; // перебираем все отмеченные измерения и добавляем их к запросу foreach (var i in listBox.SelectedItems) { query += " " + i.ToString() + ".ALLMEMBERS *"; } // удаляем последний пробел со звездочкой query = query.Remove(query.Length - 2); // при наличии фильтра дописываем условие вида "[Measures].[Hits Count] > 500" query += filter ? "} , [Measures].[Hits Count] " + cbFilterMode.SelectedValue.ToString() + " " + Convert.ToInt32(txtFilterValue.Text) + ")" : ""; //финальная часть запроса query += " } ON ROWS FROM [Почта]"; UpdateChart(query); } } } 

exception occurs

  // выполняем запрос, получаем CellSet CellSet cs; cs = mdCommand.ExecuteCellSet(); 

 Необработанное исключение типа "Microsoft.AnalysisServices.AdomdClient.AdomdErrorResponseException" в Microsoft.AnalysisServices.AdomdClient.dll 

  <ListBox x:Name="listBox" HorizontalAlignment="Left" Height="385" Margin="10,10,0,0" VerticalAlignment="Top" Width="230" FontFamily="Segoe UI Black" Grid.Column="10"> <ListBox.ItemTemplate> <DataTemplate> <CheckBox Content="{Binding Text}" IsChecked="{Binding Checked ,Mode=TwoWay}" Click="CheckBox_Click"/> </DataTemplate> </ListBox.ItemTemplate> </ListBox> 
  • You looked at debugging at what point the program stops? Maybe Exseption crashes somewhere, try framing all code in functions in try {} catch (Exseption ex) {MessageBox.Show (ex.Message); } - Alexsandr Ter
  • @AlexsandrTer is not what is happening, only GetDimensions () is executed - Sergey74rus

1 answer 1

Try adding a DataGrid.Items.Refresh() :

 // обновляем визуализацию данных try { dataGrid.ItemsSource = Data.DefaultView; dataGrid.Items.Refresh(); } 

In general, when using WPF, you need to apply bindings (Bindings) and the MVVM pattern. The code immediately becomes "on the shelves."

  • did not help, also the data is not recorded - Sergey74rus
  • @ Sergey74rus: how and where do you call BuildQuery ()? I see that it is declared private . - badc0de32
  • I have now done something to call it via the button, I looked through breakpoin and did not read the value of the selected checkbox from the listBox, tried the listBox.SelectedItems.Count in this way, do not tell me another option? - Sergey74rus
  • @ Sergey74rus: I don’t understand how your listBox is implemented. Show his xaml markup. Try to go from simple to complex: first, in BuildQuery (), make a query with a fixed string that is guaranteed to receive data from the database and send it to the dataGrid. - badc0de32
  • I changed the question, I got a checkbox from the listBox, but now another problem - Sergey74rus