按照以下正确设置时,没有理由刷新、重新加载或无效。
要在添加新项目时立即看到更改,请使用 BindingList 和 BindingSource 进行设置。然后将新项目添加到 BindingList。
还可以考虑在模型中的属性值更改时使用 INotifyPropertyChanged。
使用以下模型
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Newtonsoft.Json;
using North.Interfaces;
namespace North.Models
{
public partial class Contacts : INotifyPropertyChanged
{
private string _firstName;
private string _lastName;
private int? _contactTypeIdentifier;
public int Id => ContactId;
public int ContactId { get; set; }
public string FirstName
{
get => _firstName;
set
{
_firstName = value;
OnPropertyChanged();
}
}
public string LastName
{
get => _lastName;
set
{
_lastName = value;
OnPropertyChanged();
}
}
public int? ContactTypeIdentifier
{
get => _contactTypeIdentifier;
set
{
_contactTypeIdentifier = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
然后在表单中,加载数据到BindingList,添加按钮添加一条新记录并显示新的主键。
namespace North.Forms
{
public partial class ContactAddForm : Form
{
private BindingList<Contacts> _bindingList;
private readonly BindingSource _bindingSource = new BindingSource();
public ContactAddForm()
{
InitializeComponent();
dataGridView1.AutoGenerateColumns = false;
Shown += OnShown;
}
private void OnShown(object sender, EventArgs e)
{
using (var context = new NorthwindContext())
{
_bindingList = new BindingList<Contacts>(context.Contacts.ToList());
_bindingSource.DataSource = _bindingList;
dataGridView1.DataSource = _bindingSource;
}
_bindingSource.MoveLast();
}
private void AddNewContactButton_Click(object sender, EventArgs e)
{
// hard coded contact
var newContact = new Contacts()
{
FirstName = "Karen",
LastName = "Payne",
ContactTypeIdentifier = 1
};
// add to list and display in DataGridView
_bindingList.Add(newContact);
// save changes
using (var context = new NorthwindContext())
{
context.Add(newContact).State = EntityState.Added;
context.SaveChanges();
}
// See new primary key
MessageBox.Show("Id " + newContact.ContactId.ToString());
}
}
}
编辑
在 DataGridView 中查看当前行的值
private void CurrentContactButton_Click(object sender, EventArgs e)
{
Contacts current = _bindingList[_bindingSource.Position];
MessageBox.Show($"{current.ContactId}, {current.FirstName}, {current.LastName}");
}