2017-01-31 6 views
0

Я знаю, что здесь есть куча вопросов и множество информации в другом месте. По какой-то причине я не могу заставить это работать. Вот одна из моих отправных точек ... Add entire row to DataTable at once using listWPF Datagrid C#

Это список списков. В самом первом списке должны быть заголовки столбцов.

dat является List<List<string>>, который выглядит как:

{"index", "filename0", "filename1"}, 
{"A-100", "yes", "no"}, 
{"A-200", "no", "yes"} 
etc... 

Код:

/// Dictionary containing as Key => FileName 
    /// as Value => All drawing numbers found in FileName 
    Dictionary<string, List<string>> AllDrawingLists = new Dictionary<string, List<string>>(); 

    private void processGrid() 
    { 
     List<string> index = new List<string>(); 

     /// Build a comprehensive INDEX from the dictionary - A list 
     /// of all the drawing numbers found in all the FIlenames 
     foreach (KeyValuePair<string, List<string>> item in AllDrawingLists) 
     { 
      foreach (string dwg in item.Value) 
      { 
       if (index.Contains(dwg) == false) 
       { 
        index.Add(dwg);     } 
      } 
     } 

     List<List<string>> dat = new List<List<string>>(); 
     List<String> headers = new List<string>(); 
     headers.Add("Index"); 

     foreach (KeyValuePair<string, List<string>> item in AllDrawingLists) 
     { 
      headers.Add(item.Key); 
     } 
     dat.Add(headers); 


     foreach(string i in index) 
     { 
      List<string> row = new List<string>(); 
      row.Add(i); 
      foreach(KeyValuePair<string, List<string>> item in AllDrawingLists) 
      { 
       string cell = "no"; 
       if (item.Value.Contains(i)) 
       { 
        cell = "yes"; 
       } 
       row.Add(cell); 
      } 
      dat.Add(row); 
     } 

     dataGrid.Columns.Clear(); 
     DataTable dt = new DataTable(); 
     int ii = 0; 
     foreach (List<string> row in dat) 
     { 

      if (ii == 0) 
      { 
       foreach(string t in row) 
       { 
        dt.Columns.Add(t); 
       } 
       ii++; 
      } else 
      { 
       dt.Rows.Add(row.ToArray<string>()); 
      } 
     } 
     dataGrid.ItemsSource = dt.AsDataView(); 
    } 

Мой ожидаемый результат будет:

|  |  |  | 
| index | file1 | file2 | 
------------------------- 
| A-100 | yes | no | 
------------------------- 
| A-200 | no | yes | 
------------------------- 
| A-300 | yes | yes | 

, но вместо этого я получаю:

|  |  |  | 
| index | file1 | file2 | 
------------------------- 
| A-100 |  |  | 
------------------------- 
| A-200 |  |  | 
------------------------- 
| A-300 |  |  | 

Список списков - это то, чего я ожидал бы, явно работая над определением столбцов. Я не уверен, почему ничего не происходит в DataGrid после первого столбца

Вот результат dat. Это то, что я думаю, что я ищу. Учитываются все строки и столбцы. Index C:\py\narrver2\lists.txt C:\py\narrver2\list2.docx A-1001 yes yes A-1002 yes yes A-1003 yes yes A-1004 no yes A-1005 no yes A-1006 no yes A-1007 no yes

+0

Вы правильно инициализировали свой список списков? Потому что я просто проверил ваш код и заставил его работать на меня. –

+0

Спасибо. Я не уверен. Я начал C# около недели назад и все еще получаю удовольствие от этого. Я добавил весь класс. –

+0

Я думаю, проблема связана с вашим списком инициализации списков. Я не уверен, что содержит 'AllDrawingLists'. Проверьте это, чтобы убедиться, что вы их правильно. Вы можете попробовать с помощью 'Console.Write()' каждый элемент в списке, как 'Еогеасп (Список listDat в Дат) { Еогеасп (строка strDat в listDat) { Console.Write (strDat +" «); } Console.WriteLine(); } ' –

ответ

0

Если вы хотите сохранить точку в имени заголовка, вы можете установить путь связывания столбца заголовка с именем заголовка, окруженным квадратными скобками, чтобы создать специальный символ (в этом случае обозначение точки) сбежал.

Вы можете сделать это внутри обработчика событий, который подписывается на событие AutoGeneratingColumn вашего DataGrid.

private void dataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e) 
{ 
    if (e.PropertyName.Contains('.') && e.Column is DataGridBoundColumn) 
    { 
     DataGridBoundColumn dataGridBoundColumn = e.Column as DataGridBoundColumn; 
     dataGridBoundColumn.Binding = new Binding("[" + e.PropertyName + "]"); 
     dataGridBoundColumn.SortMemberPath = e.PropertyName; 
    } 
} 
Смежные вопросы