Search code examples
wpfmvvmdatagrid

Using Mvvm How to get data in Datagrid wpf?


I want to execute the data grid and enter the data in the row of the data grid and save the data in the database when I press the button. How do I get the new Data Grid row in the MVVM format?


Solution

  • I recommend creating a form that specifically adds data into the database then refresh the item source of the data grid.

    <DataGrid x:Name="dataGrid"  ItemsSource="{Binding ProductCollection}"  Grid.Row="1" AutoGenerateColumns="False" VirtualizingPanel.IsVirtualizing="True">
            <DataGrid.Columns>
                <DataGridTextColumn Header="DATE ADDED" Binding="{Binding DateAdded}" Width="Auto" />
                <DataGridTextColumn Header="PRODUCT ID" Binding="{Binding Id}" Width="*"/>
                <DataGridTextColumn Header="PRODUCT NAME" Binding="{Binding Name}" Width="*" />
                <DataGridTextColumn Header="CATEGORY" Binding="{Binding CategoryName}" Width="*" />
            </DataGrid.Columns>
    </DataGrid>
    

    Sample Form:

    <StackPanel MinWidth="250" MaxWidth="250">
        <TextBox  Margin="10" Text="{Binding NewId,UpdateSourceTrigger=PropertyChanged}"  MinHeight="38" />
        <TextBox  Margin="10" Text="{Binding NewName,UpdateSourceTrigger=PropertyChanged}"  MinHeight="38"/>
        <Button Command="{Binding InsertCommand}">Save</Button>
    </StackPanel>
    

    For the ViewModel

    public ObservableCollection<ProductModel> ProductCollection { get; set; } = new ObservableCollection<ProductModel>();
    

    After inserting the data into the database, just create a new product object using the data from the form then add it to the collection(ProductCollection). It will automatically refresh the datagrid.

    ProductModel item = new ProductModel();
    item.id = NewId;
    item.Name = NewName;
    ProductCollection.Add(item);
    

    In the context of refreshing the data, I do not recommend this method of creating an object then insert it to the collection rather than clearing the collection then re-retrieve the data from the database if your program has multiple users.