This example describes how to allow user to add a new row in WinUI DataGrid.
WinUI 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 SfDataGrid.AddNewRowPosition property. You can also set the position of built-in AddNewRow through AddNewRowPosition property.
When you start editing in AddNewRow, the WinUI 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.
You can commit or cancel a new row from being added by pressing the Enter and Esc key respectively.
<syncfusion:SfDataGrid x:Name="dataGrid"
AddNewRowPosition="Top"
AllowEditing="True"
ItemsSource="{Binding ProductInfo}">
You can add a new row by using SfDataGrid.View.AddNew and SfDataGrid.View.CommitNew methods.
private void Button_Click(object sender, RoutedEventArgs e)
{
this.dataGrid.View.AddNew();
this.dataGrid.View.CommitNew();
}
WinUI DataGrid enables you to customize the watermark text of AddNewRow by changing value of AddNewRowText in Resource Designer.
You can go through this user guide to know more about customizing default string of AddNewRow’s text.
WinUI DataGrid allows you to set the default values for AddNewRow while initiating through AddNewRowInitiatingEventArgs.NewObject property in SfDataGrid.AddNewRowInitiating event.
dataGrid.AddNewRowInitiating += OnAddNewRowInitiating;
private void OnAddNewRowInitiating(object sender, Syncfusion.UI.Xaml.DataGrid.AddNewRowInitiatingEventArgs e)
{
var data = e.NewObject as ProductSalesDetails;
data.Product = "Car";
data.Country = "UK";
data.State = "Scotland";
data.Quantity = 5;
data.Discount = 12;
data.Amount = 200000;
}
Take a moment to peruse the WinUI DataGrid - Add new rows documentation, where you can find about add new rows with code examples.
Visual Studio 2019 and above versions