How to allow user to add a new row in WPF DataGrid?
In WPF DataGrid (SfDataGrid) provides built-in row called AddNewRow. It allows user to add a new row to underlying collection. You can enable or disable by setting DataGrid.AddNewRowPosition property. You can also set the position of built-in AddNewRow through AddNewRowPosition property.
When you start editing in AddNewRow, the DataGrid control creates an instance for the underlying data object and adds it to underlying collection when editing completed. So, the underlying data object must be defined with default constructor.
<syncfusion:SfDataGrid x:Name="dataGrid"
ItemsSource="{Binding Orders}"
AddNewRowPosition="Top">
</syncfusion:SfDataGrid>
Add a new row programmatically to WPF DataGrid
private void Button_Click(object sender, RoutedEventArgs e)
{
dataGrid.View.AddNew();
this.dataGrid.View.CommitNew();
}WPF DataGrid allows you to set the default values for AddNewRow while initiating through AddNewRowInitiatingEventArgs.NewObject property in DataGrid.AddNewRowInitiating event.
dataGrid.AddNewRowInitiating += DataGrid_AddNewRowInitiating;
private void DataGrid_AddNewRowInitiating(object sender, AddNewRowInitiatingEventArgs e)
{
var data = e.NewObject as OrderInfo;
data.OrderID = 1000;
data.CustomerID = "BERGS";
data.CustomerName = "Hanna";
data.Country = "UK";
data.ShipCity = "London";
}
Take a moment to peruse the WPF DataGrid - AddNewRow, where you can find about built-in AddNewRow feature, with code examples.