When I select itemsource from datagrid, the value is null. Is it because I did not define imtemsource in datagrid?
This is how I add in a row into the datagrid:
this.dgProductList.Items.Add(new {ProductId=product.ProductId, Name=product.Name, Qty=1, Price=product.Price});
Here is my wpf:
<DataGrid Name="dgProductList"
AutoGenerateColumns="False"
FontSize="15"
HorizontalGridLinesBrush="#f0f0f0"
VerticalGridLinesBrush="#f0f0f0"
ScrollViewer.CanContentScroll="False"
ScrollViewer.VerticalScrollBarVisibility="Auto"
ScrollViewer.HorizontalScrollBarVisibility="Auto">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Image">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image Height="10" Width="10" Source="{Binding Picture}" Stretch="Uniform"></Image>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Binding="{Binding ProductId}" Visibility="Hidden"/>
<DataGridTextColumn Binding="{Binding Name}" Header="Item" />
<DataGridTextColumn Binding="{Binding Qty}" Header="Qty" />
<DataGridTextColumn Binding="{Binding Price}" Header="Price" />
<DataGridTemplateColumn Width="*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Button Width="30" Name="btnDecrease" Content="-" />
<Button Width="30" Name="btnIncrease" Content="+" />
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
you must use ItemsSource property of your grid
like
or
You should use binding to add items to datagrid:
And in your view model (or something that is assigned to DataSource of your view):
ObservableCollection is the one to use in wpf binding because it implements pattern that allows datagrid to react to changes in this collection.