可编辑的DataGridView绑定到List

时间:2013-05-29 08:09:09

标签: c# winforms data-binding

我有一个绑定到列表的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或其他内容?

1 个答案:

答案 0 :(得分:4)

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

相关问题