绑定到列表的可编辑DataGridView
本文关键字:编辑 DataGridView 列表 绑定 | 更新日期: 2023-09-27 18:15:44
我有一个绑定到列表的DataGridView。值显示良好,当我单击一个值时,它开始编辑,但是当我按Enter时,更改被忽略,没有数据被更改。当我在Value setter中放置一个断点时,我可以看到它在编辑后被执行,但是没有显示任何更改的数据。我的绑定代码是这样的:
namespace DataGridViewList
{
public partial class Form1 : Form
{
public struct LocationEdit
{
public string Key { get; set; }
private string _value;
public string Value { get { return _value; } set { _value = value; } }
};
public Form1()
{
InitializeComponent();
BindingList<LocationEdit> list = new BindingList<LocationEdit>();
list.Add(new LocationEdit { Key = "0", Value = "Home" });
list.Add(new LocationEdit { Key = "1", Value = "Work" });
dataGridView1.DataSource = list;
}
}
}
该项目是一个基本的Windows窗体项目,在设计器中创建了一个DataGrid,列称为Key和Value,并将DataPropertyName分别设置为Key/Value。没有值被设置为只读
我是不是漏掉了什么步骤?我需要实现INotifyPropertyChanged
,还是其他什么?
问题是您正在使用struct
作为BindingList项目类型。解决方案是你应该把struct
改为class
,它工作得很好。然而,如果你想继续使用struct
,我有一个想法,使它的工作,当然,它需要更多的代码比简单地改变struct
到class
。整个思想是每当一个单元格的值发生变化时,底层的项(这是一个结构体)应该被分配给一个全新的结构体项。这是您可以用来更改底层值的唯一方法,否则提交更改后的单元格值将不会更改。我发现事件CellParsing
是一个适合这种情况下添加自定义代码,这是我的代码:
namespace DataGridViewList
{
public partial class Form1 : Form
{
public struct LocationEdit
{
public string Key { get; set; }
private string _value;
public string Value { get { return _value; } set { _value = value; } }
};
public Form1()
{
InitializeComponent();
BindingList<LocationEdit> list = new BindingList<LocationEdit>();
list.Add(new LocationEdit { Key = "0", Value = "Home" });
list.Add(new LocationEdit { Key = "1", Value = "Work" });
dataGridView1.DataSource = list;
}
//CellParsing event handler for dataGridView1
private void dataGridView1_CellParsing(object sender, DataGridViewCellParsingEventArgs e){
LocationEdit current = ((BindingList<LocationEdit>)dataGridView1.DataSource)[e.RowIndex];
string key = current.Key;
string value = current.Value;
string cellValue = e.Value.ToString()
if (e.ColumnIndex == 0) key = cellValue;
else value = cellValue;
((BindingList<LocationEdit>)dataGridView1.DataSource)[e.RowIndex] = new LocationEdit {Key = key, Value = value};
}
}
}
我不认为继续这样使用struct
是个好主意,class
会更好。