A simple WPF DataGrid application to show the ProductName and ProductID from Database using Entity Framework.

  1. Create a new WPF Project.

  2. Rename the Main window to DataGridSample.xaml( Make sure you rename the StartupUri in App.xaml too).

  3. Drag and drop DataGrid to this window and Name it ProductDataGrid.

  4. <DataGrid Name="ProductDataGrid"  AutoGenerateColumns="False" Height="120" Width="350" Margin="10" />

  5. Create a table named "Products" in your Database( I use SQL Server 2008)



  6. Create Model Classes with the Entity Framework.
  7. Create Model.

  8. Create an instance of this Model in your Codebehind class.(Here the ProductEntity)

  9. ProductEntities _Product = new ProductEntities();

  10. Use this LINQ query to get the ProductName and ProductID

  11. var prod = from p in _customer.Products
    select new { ProdId = p.ProductId, ProdName = p.ProductName };

  12. We have to bind the DataGrid columns are bind to ProdID and ProdName, so we have to add this code to the DataGrid Control in the DataGridSample.xaml


  13. <DataGrid Name="ProductDataGrid" AutoGenerateColumns="False" Height="120"  Width="350" Margin="10" ItemsSource="{Binding}" >
    <DataGrid.Columns>
    <DataGridTextColumn Header=" Product Name" Binding="{Binding ProdId}"/>
    <DataGridTextColumn Header=" Product Name" Binding="{Binding ProdName}"/>
    </DataGrid.Columns>
    </DataGrid>

  14. Use DataContext to bind DataGrid to "prod".
ProductDataGrid.DataContext = prod;

DataBindingSample.cs
------------------------
public partial class DataBindingSample: Window
{
//Model class Instance.
ProductEntities _Product;

public DataBindingSample()
{
InitializeComponent();
_Product = new ProductEntities();
var prod = from p in _Product.Products
select new { ProdId = p.ProductId,
ProdName = p.ProductName };
ProductDataGrid.DataContext = prod;
}
}


DataBindingSample.xaml
------------------------
<StackPanel>
<DataGrid Name="ProductDataGrid" AutoGenerateColumns="False" Height="120" Width="300" Margin="10" ItemsSource="{Binding}" >
<DataGrid.Columns>
<DataGridTextColumn Header=" Product ID" Binding="{Binding ProdId}"/>
<DataGridTextColumn Header=" Product Name" Binding="{Binding ProdName}"/>
</DataGrid.Columns>
</DataGrid>
</StackPanel>



0 comments:

Post a Comment