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

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

myDataGrid.ItemsSource = myList 

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

 myDataGrid.ItemsSource = myDataTable.DefaultView 

My DataGrid's AutoGenerateColumns property is set to 'True'. And for datatable, this works fine, but when I assign List (Of String) to ItemsSource, my column name is displayed as β€œLength” and the data displayed is integers, which are the number of characters in each String element in the list, not actual String element.

What am I doing wrong?

EDIT

My test list is created as follows:

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

The following two methods give accurate results.

Create CollectionView:

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

Just use the List:

 DataGrid1.ItemsSource = myList 

Both of these methods map a single column in the DataGrid. The column is called "Length" and contains integers corresponding to the length of each row.

EDIT

Translation of "testalino" in VB:

 DataGrid1.ItemsSource = myList.Select(Function(s) New With {.Value = s}).ToList 
+6
list visual-studio-2010 wpf datagrid
source share
1 answer

Your business is really funny. You bind the elements of the type string to the grid. The grid then searches for properties of 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 to create a wrapper class for the string.

Or create a class explicitly:

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

or 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.

+4
source share

All Articles