C# 我可以控制DataGridView何时从/向其数据源读取和写入数据吗?
我绑定到一个C# 我可以控制DataGridView何时从/向其数据源读取和写入数据吗?,c#,winforms,datagridview,.net-4.0,C#,Winforms,Datagridview,.net 4.0,我绑定到一个列表,当我在MyCustomType中的属性获取程序上设置断点时,它们似乎被重复调用。是什么导致DataGridView自动重新读取数据?我可以控制吗 其次,我注意到,当我对网格中的数据进行更改时,这些更改不会立即复制到数据源。在MyCustomType中的属性设置器上放置断点,似乎只有在我在网格控件外单击时才会调用断点。如何确保GUI中所做的更改立即应用于数据源?从属性中重新读取是完全正常的,这是因为渲染。当DataGridView呈现单元格时,它从属性中读取 支持: 如果希望属性
列表
,当我在MyCustomType
中的属性获取程序上设置断点时,它们似乎被重复调用。是什么导致DataGridView
自动重新读取数据?我可以控制吗
其次,我注意到,当我对网格中的数据进行更改时,这些更改不会立即复制到数据源。在
MyCustomType
中的属性设置器上放置断点,似乎只有在我在网格控件外单击时才会调用断点。如何确保GUI中所做的更改立即应用于数据源?从属性中重新读取是完全正常的,这是因为渲染。当DataGridView
呈现单元格时,它从属性中读取
支持:
如果希望属性的更改对DataGridView
可见,则应实现双向数据绑定。这会使对象中的更改立即在栅格中可见:
using System.ComponentModel;
using System.Runtime.CompilerServices;
public class Category : INotifyPropertyChanged
{
#region Properties
private int _Id;
public int Id
{
get
{
return _Id;
}
set
{
if (_Id == value)
return;
_Id = value;
OnPropertyChanged();
}
}
private string _Name;
public string Name
{
get
{
return _Name;
}
set
{
if (_Name == value)
return;
_Name = value;
OnPropertyChanged();
}
}
#endregion
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var eventHandler = this.PropertyChanged;
if (eventHandler != null)
eventHandler(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
- 如果您使用的是.Net 4.5,请删除
,并且在调用[CallerMemberName]
时,只需传递属性名称,例如OnPropertyChanged
OnPropertyChanged(“名称”)
list
如果使用List
,则应将数据源设置为null,然后再次设置为列表,以使更改对网格可见
BindingList<Category> source = new BindingList<Category>();
private void Form_Load(object sender, EventArgs e)
{
//Load Data to BindingList
new List<Category>()
{
new Category(){Id=1, Name= "Category 1"},
new Category(){Id=2, Name= "Category 2"},
}.ForEach(x=>list.Add(x));
this.categoryDataGridView.DataSource = list;
}
private void toolStripButton1_Click(object sender, EventArgs e)
{
//Add data to BindingList
//Data will be visible to grid immediately
list.Add(new Category(){Id=3, Name= "Category 3"});
}
- 我个人不建议所有列都使用这种技巧,例如,假设您有一个验证最小字符串长度为5的字符串属性,现在如何向它输入5个字符,那么在输入5个字符之前,您将收到5条验证错误消息李>
仔细选择你需要的东西。@Dylan不,这是一个普通的WinFormsproject@Mr.Boy如果您对解决方案有任何疑问,请告诉我:)谢谢-但是我可以控制验证何时完成,以便立即更新我的模型吗?我发现,若我切换一个复选框,那个么只有当我点击一个不同的单元格时,模型才会更新。我需要用户能够看到的东西,以便在用户更改某些内容时始终表示模型。我认为这个问题可能是对#2的回答,但我还没有测试。您好,我收到一个编译错误,
[CallerMemberName]
未知。。。我是否需要使用参考或.NET版本的特定?@Mr.Boy使用System.Runtime.CompilerServices代码>和.NET4。5@Mr.Boy如果您使用的是.NET4.0,只需删除该属性并将属性名传递给方法,例如OnPropertyChanged(“name”)代码>
private void categoryDataGridView_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (categoryDataGridView.IsCurrentCellDirty)
{
categoryDataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}