Reputation: 191
i want to add a new row in data grid of WPF with specific data each time I click a button, where rows will be one after another.However my code is just replacing the previous on not adding a new one below it: here is my code behind:
ObservableCollection<DataItem> items = new ObservableCollection<DataItem>();
items.Add(new DataItem() { Product = product, Quantity = qnt.ToString(), Price = price, Total = totalPrice.ToString() });
dataGrid.ItemsSource = items;
"dataGrid" is the name in the XAML. Can anyone help!
Upvotes: 0
Views: 1274
Reputation: 169270
Create the ObservableCollection and set the ItemSource property of the DataGrid once, for example in the constructor of your window or user control. Make sure that you store a reference to the ObservableCollection in the class:
public partial class MainWindow : Window
{
ObservableCollection<DataItem> items = new ObservableCollection<DataItem>();
public MainWindow()
{
InitializeComponent();
items.Add(new DataItem() { Product = product, Quantity = qnt.ToString(), Price = price, Total = totalPrice.ToString() });
dataGrid.ItemsSource = items;
}
}
You will then able able to add new items to the same ObservableCollection from any other method of class including your Click event handler:
private void Button_Click(object sender, RoutedEventArgs e)
{
items.Add(new DataItem() { Product = product, Quantity = qnt.ToString(), Price = price, Total = totalPrice.ToString() });
}
Upvotes: 0
Reputation: 4464
There is no need to bind the Datagrid to an observable collection. If you want to do so, then please have a look at MVVM pattern for WPF. If you just want to add a row to the datagrid, use this code :
DataGrid.Items.Add(new DataItem() { Product = product, Quantity = qnt.ToString(), Price = price, Total = totalPrice.ToString() });
Also consider adding a datatable as the source by checking out this answer.
Upvotes: 1