Here is an example that has a table as follows
Form interface
Using EF Core 5 and a custom BindingList which allows the DataGridView to be sortable (not needed for your question but nice and if you want it I can post the source)
using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using WindowsFormsApp1.Classes;
using WindowsFormsApp1.Data;
using WindowsFormsApp1.Models;
namespace WindowsFormsApp1
{
/// <summary>
/// C# 9
/// </summary>
public partial class Form1 : Form
{
private readonly BindingSource _bindingSource = new ();
/// <summary>
/// Custom BindingList to allow the DataGridView to be sortable
/// </summary>
private SortableBindingList<Country> _countryBindingList;
public Form1()
{
InitializeComponent();
Shown += OnShown;
}
private void OnShown(object? sender, EventArgs e)
{
using var context = new Context();
_countryBindingList = new SortableBindingList<Country>(context.Country.ToList());
_bindingSource.DataSource = _countryBindingList;
dataGridView1.DataSource = _bindingSource;
}
private void LastIdButton_Click(object sender, EventArgs e)
{
using var context = new Context();
/*
* If no record, add one with a default value for a country name,
* in reality this would need input from the user e.g. a ComboBox
* selection
*/
if (!context.Country.Any())
{
Country newCountry = new Country() {Name = "TODO"};
context.Country.Add(newCountry);
context.SaveChanges();
LastIdTextBox.Text = newCountry.Id.ToString();
NextIdTextBox.Text = (newCountry.Id + 1).ToString();
}
/*
* We have at least one record, get the last record
* From the last record get the key, id and display
* the current last id and another text box the last id
* plus one.
*/
else
{
Country country = context.Country.OrderBy(countryItem => countryItem.Id).LastOrDefault();
LastIdTextBox.Text = country.Id.ToString();
NextIdTextBox.Text = (country.Id + 1).ToString();
}
}
}
}
In regards to the custom BindingList, to get the current record in the DataGridView
var currentCountry = _countryBindingList[_bindingSource.Position];