Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a List(Of T) as Itemssource for a WPF DataGrid?

I wanted to quickly display a List(OF String) in a DataGrid (dynamically), so I thought

myDataGrid.ItemsSource = myList

would be the quick and easy way to do it, since this works great for a DataTable:

myDataGrid.ItemsSource = myDataTable.DefaultView

My DataGrid has the AutoGenerateColumns property set to 'True'. And for the datatable this works fine, but when I assign the List(Of String) to the ItemsSource, my column name shows up as 'Length' and the displayed data are integers that are the number of characters in each String item in the List, not the actual String item.

What am I doing wrong?

EDIT

My test list is created like this:

Dim myList As New List(Of String)
  For i As Int32 = 1 To 25
  myList.Add("Item #" & i)
Next

The following 2 methods produce the exact same results.

Create a CollectionView:

Dim cv = CType(CollectionViewSource.GetDefaultView(myList), CollectionView)
DataGrid1.ItemsSource = cv

Just use the List:

DataGrid1.ItemsSource = myList

Both of these methods display a single column in the DataGrid. The column is titled 'Length' and contains integers matching the length of each string entry.

EDIT

Translation of answer by 'testalino' to VB:

DataGrid1.ItemsSource = myList.Select(Function(s) New With {.Value = s}).ToList
like image 635
GSTD Avatar asked Oct 20 '10 10:10

GSTD


1 Answers

Your case is actually funny. You are binding elements of type string to a grid. The grid then looks for properties in type String that it can display. the only property found is Length, so it creates a column named Length and displays its value.

What you need to do to avoid this is create a wrapper class for string.

Either create a class explicitly:

class StringWrapper
{
     string Value { get; set;}
}

or by using LINQ:

List<string> strings = new List<string>();
strings.Add("abc");
strings.Add("def");
dataGrid.ItemsSource = strings.Select(s => new { Value = s }).ToList();

Hope this helps.

like image 86
testalino Avatar answered Oct 04 '22 03:10

testalino