Hi, @RogerSchlueter-7899. Welcome to Microsoft Q&A.
You could insert data to the top of DataGrid
using DataTable.Rows.InsertAt(newRow,0);
Reference sample code
MainWindow.xaml
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="3*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<DataGrid x:Name="MyDataGrid" RowEditEnding="MyDataGrid_RowEditEnding">
</DataGrid>
<Button Grid.Row="1" Width="200" Content="Add NewRow" Height="50" Click="Button_Click"></Button>
</Grid>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
DataTable dt = new DataTable();
public MainWindow()
{
InitializeComponent();
//Defining initial data
dt.Columns.Add("Column1");
dt.Columns.Add("Column2");
dt.Rows.Add("Row1Column1", "Row1Column2");
dt.Rows.Add("Row2Column1", "Row2Column2");
//Binding
MyDataGrid.ItemsSource = dt.DefaultView;
var i = (IEditableCollectionView)MyDataGrid.Items;
i.NewItemPlaceholderPosition = NewItemPlaceholderPosition.AtBeginning;
}
//Adding New Data
private void Button_Click(object sender, RoutedEventArgs e)
{
DataRow newRow = dt.NewRow();
newRow["Column1"] = "Row3Column1";
newRow["Column2"] = "Row4Column1";
dt.Rows.InsertAt(newRow,0);
}
private void MyDataGrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
{
var dataGrid = sender as DataGrid;
var collectionView = (IEditableCollectionView)dataGrid.Items;
if (collectionView.IsAddingNew)
{
// Get the DataRowView of the new row
var newItem = collectionView.CurrentAddItem as DataRowView;
if (newItem != null)
{
// Complete the adding operation
collectionView.CommitNew();
// Get the bound DataTable
var dataTable = ((DataView)dataGrid.ItemsSource).Table;
if (dataTable != null)
{
// Insert a new row at the top of the DataTable
var newRow = newItem.Row;
dataTable.Rows.Remove(newRow); // Remove the current line first
dataTable.Rows.InsertAt(newRow, 0); // Insert at top
}
}
}
}
}
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.