2013-05-29 113 views
4

我有一个DataGridView绑定到列表。值显示很好,当我点击一个值时,它开始编辑,但是当我按下Enter时,这个改变被忽略了,没有数据被改变。当我在Value setter中放置一个断点时,我可以看到它在编辑之后执行,但没有显示更改过的数据。我的绑定代码如下所示:可编辑的DataGridView绑定到列表

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的列称为键和值分别设置DataPropertyName以键/值。没有值被设置为只读。

有没有我失踪的一些步骤?我需要实施INotifyPropertyChanged还是其他?

+1

你能展示一些更多的代码吗?例如,像编辑/确认事件处理程序? –

+0

@PiotrJustyna我没有这样的处理程序。我必须添加一个吗? – Suma

+0

发生什么事情是您的数据网格对基础列表中的更改一无所知。每次更改该值时,请使用ResetBindings方法(http://msdn.microsoft.com/zh-cn/library/system.windows.forms.control.resetbindings.aspx)通知网格。 –

回答

3

问题是您正在使用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会更好。