Re: Lists to DataGridViews
You need to set up data-binding, expose what columns to be display (you can also copy them into a new class/struct properties) then bind them in the xaml.
Re: Lists to DataGridViews
Code:
PropertyDescriptorCollection properties =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
foreach (PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
foreach (T item in data)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
return table;
This is what I found online and it seems to work. You feed in the object that defines your list and it figures out the appropriate columns.
So my process is load the list, load the table with modified code above, and then bind it to the data grid view.
Re: Lists to DataGridViews
Awesome! Here is another way to bind a list to datagrid using XAML
Code:
<DataGrid AutoGenerateColumns="False" Height="172"
HorizontalAlignment="Stretch"
Name="dgSkypeMate" VerticalAlignment="Top" HorizontalGridLinesBrush="#FFCECBCB"
VerticalGridLinesBrush="#FFCECBCB" MinRowHeight="10" FontFamily="Times New Roman"
FontSize="13" FontStretch="Normal"
Background="Azure" RowBackground="White" AlternatingRowBackground="Lavender"
HorizontalScrollBarVisibility="Visible"
VerticalScrollBarVisibility="Visible"
IsReadOnly="True" ItemsSource="{Binding}"
Foreground="Black" SelectionChanged="dgSkypeMate_SelectionChanged" Margin="7,0,11,0"
BorderBrush="#FFC4C4C4"
ItemContainerStyle="{StaticResource alternatingDataGridItemStyle}"
UseLayoutRounding="True"
ColumnHeaderHeight="33"
ContextMenuService.ShowOnDisabled="False"
>
<DataGrid.Columns>
<DataGridTextColumn Header="Skypemate ID" MinWidth="100" Width="150" Binding="{Binding Path=idStr}" />
<DataGridTextColumn Header="Display name" Binding="{Binding Path=dispStr}" MinWidth="120" Width="220" />
<DataGridTextColumn Header="Last Online" MinWidth="100" Width="150" Binding="{Binding Path=lastOnlineStr}" />
</DataGrid.Columns>
<DataGrid.ContextMenu>
<ContextMenu Name="conmenu" IsEnabled="True">
<MenuItem Header="Delete" Click="MenuItem_Click"/>
</ContextMenu>
</DataGrid.ContextMenu>
</DataGrid>
That is a piece I took from my current tiny do-it-myself project. "Binding Path= [name of an existing object you want to display your data through and with its value]"