WPF - fill data on data grid

c#, wpf, wpf-controls, wpfdatagrid

Solution

Assign users (collection) as a ItemsSource of DataGrid to display the data on datagrid.

XAML

<Window x:Class="WpfApplication1.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="300" Width="500">
    <StackPanel>
        <Grid x:Name="Grid" Background="#FF1BA1E2">
            <DataGrid x:Name="DataGrid" HorizontalAlignment="Left" Margin="65,10,0,0" VerticalAlignment="Top" Height="180" Width="385" SelectionChanged="DataGrid_SelectionChanged_1"/>
            <Button Content="Button" HorizontalAlignment="Left" Margin="95,235,0,0" VerticalAlignment="Top" Width="75" Height="30" Click="Button_Click_1"/>
        </Grid>
    </StackPanel>
</Window>

Code behind

//Fill data here
private void Button_Click_1(object sender, RoutedEventArgs e)
{

            ObservableCollection<User> users = new ObservableCollection<User>();
            users.Add(new User{FirstName = "firstname-1",LastName = "lastname-1"});
            users.Add(new User{FirstName = "firstname-2",LastName = "lastname-2"});
            users.Add(new User{FirstName = "firstname-3",LastName = "lastname-3"});
            users.Add(new User{FirstName = "firstname-4",LastName = "lastname-4"});
            DataGrid.ItemsSource = users;
}

That's it.

Alternatively you can define a collection property and bind it to DataGrid, instead of setting datagrid ItemsSource property from codebehind.

Problem

I have the following code and I didnt find any way how to add the data from users to table .I want to do that dynamically . I have create WPF application and add Data Grid and button and I that when I click on the button see the data on the data grid ,how should I proceed? ``` private void Button_Click(object sender, RoutedEventArgs e) { //get user data... DataTable dt = new DataTable("Users Info"); DataGrid.ItemsSource = dt.DefaultView; foreach (var user in users) { string firstName = user.Firstname; string lastName = user.Lastname; } ``` The Xaml is: ``` <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WPFTest01" x:Class="WPFTest01.MainWindow" Title="WPF_DEMO_Main" Height="350" Width="525"> <Grid x:Name="Grid" Background="#FF1BA1E2"> <DataGrid x:Name="DataGrid" HorizontalAlignment="Left" Margin="65,60,0,0" VerticalAlignment="Top" Height="185" Width="385" SelectionChanged="DataGrid_SelectionChanged_1"/> <Button Content="Button" HorizontalAlignment="Left" Margin="390,280,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1"/> </Grid> </Window> ``` I have tried with some of this code without success :( ``` //dt.Columns.Add("First Name", typeof(string)); //dt.Columns.Add("Last Name", typeof(string)); //DataSet ds = new DataSet(); //ds.Tables.Add(dt); ```

Original source