【问题标题】:DataGridView with Data Binding - new Row not showing具有数据绑定的 DataGridView - 未显示新行
【发布时间】:2018-10-05 23:21:50
【问题描述】:

我有一个DataGridView 绑定到Class1 的列表,就像my previous question 一样(顺便说一句 - the 答案是使用属性而不是字段)。然后我用以下代码添加一行:

l.Add(new Class1 { a = 5, b = 6 });

我检查了行 添加到列表中。但是DataGridView 没有更新。怎么解决的?

【问题讨论】:

  • List<T> 无法通知 Grid 内容更改(例如添加或删除元素)。我建议尝试BindingList<T>ObservableCollection<T>(+ 关于DataSource 的文档msdn.microsoft.com/en-us/library/…

标签: c# .net winforms datagridview


【解决方案1】:

如果有界源或two way bounded 中发生任何更改,您必须重新分配数据源:

grid.DataSource = null;
grid.DataSource = l;

【讨论】:

  • 谢谢。但是,数据绑定的意义难道不是要在一个中反映另一个吗?
【解决方案2】:

answer to another question of mine 也解决了这个问题。使用BindingSource 作为中间体,并使用:

bindingSource.Add(new Class1 { a = 5, b = 6 });

【讨论】:

    【解决方案3】:

    DataGridView 的属性AllowUserToAddRows 必须是true

    DataGridViewDataSource 必须是 BindingSource。它的属性AllowNew 必须是true

    您可以在 Designer 中为 DGV 创建一个BindingSource(此处命名为personBindingSource),方法是编辑其属性DataSource...BindingSourceDataSource 可能是List<Person>

    所以这很好用......

    // personBindingSource was already created in the Designer ...
    personBindingSource.DataSource = null;
    personBindingSource.DataSource = _lstPerson;
    
    dgvPerson.DataSource = personBindingSource;
    dgvPerson.Refresh();
    

    将显示新行:-)

    这不起作用...

    dgvPerson.DataSource = _lstPerson;
    dgvPerson.Refresh();
    

    DGV 仍然包含所有元素,但在这种情况下,不会显示新行:-(

    也许这会有所帮助...

    【讨论】:

      【解决方案4】:

      您应该按照以下方式设置它。在列表中添加新项目后,必须将 Datasource 设置为 null,并将其重新分配给 dataGridview。

          List<Person> lst = new List<Person>();
          private void button5_Click(object sender, EventArgs e)
          {
      
              lst.Add(new Person("X"));
              lst.Add(new Person("y"));
      
              dataGridView2.DataSource = lst;
      
              lst.Add(new Person("Z"));
      
              dataGridView2.DataSource = null;
              dataGridView2.DataSource = lst;
          }
      
       public class Person
          {
              public Person(string fname)
              {
                  this.firstname = fname;
              }
              public string firstname { get; set; }
          }
      

      【讨论】:

      • 也可以这样写——dataGridView2.DataSource = lst.ToList();
      【解决方案5】:

      您可以使用 BindingSource,这里我有一个 Datatable 的示例,当数据源中的任何内容发生更改时,它会同时反映,而无需任何刷新功能。如果要添加新行,只需要更新数据表。

      private BindingSource bindingSource = new BindingSource();
      bindingSource.DataSource = dt;
      //datagridview column binding
      ID.DataPropertyName = "ID";
      Name.DataPropertyName = "Name";
      grdCharges.DataSource = bindingSource;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-06
        相关资源
        最近更新 更多