繁体   English   中英

更改数据源时未更新 C# DataGridView

[英]C# DataGridView not updated when datasource is changed

我有一个对象列表

List<MobilePhone> results;

所以我将列表添加到 datagridview

dataGridView.DataSource = phase3Results;

所以我有几个下拉框,它们指示下拉框中所选项目的任何更改时的列表结果,所以我的列表结果发生了变化,但在 datagridview 上它没有反映。 有没有办法“刷新”更改?

快速而肮脏的解决方案

dataGridView.DataSource = null;
dataGridView.DataSource = phase3Results;

清洁和正确的解决方案

使用BindingList<T>而不是List<T>作为您的数据源。 List<T>在其集合更改时不会触发事件。

此外,如果您另外为T实现INotifyPropertyChangedBindingList<T>会自动订阅集合中每个T的属性更改,并让视图知道更改。

尝试使用 BindingList<> 而不是 List<> 并且(正如 Daniel 已经建议的那样),实现 INotifyPropertyChanged。 但是,如果您不想实现 INotifyPropertyChanged 接口,我认为您也可以调用 .Refesh() 。

这是一个从这里撕下来的例子

public class Car : INotifyPropertyChanged
 {
   private string _make;
   private string _model;
   private int _year;

  public event PropertyChangedEventHandler PropertyChanged;

  public Car(string make, string model, int year)
   {
     _make = make;
     _model = model;
     _year = year;
   }

  public string Make
   {
     get { return _make; }
     set
     {
       _make = value;
       this.NotifyPropertyChanged("Make");
     }
   }

  public string Model
   {
     get { return _model; }
     set
     {
       _model = value;
       this.NotifyPropertyChanged("Model");
     }
   }

  public int Year
   {
     get { return _year; }
     set
     {
       _year = value;
       this.NotifyPropertyChanged("Year");
     }
   }

  private void NotifyPropertyChanged(string name)
   {
     if(PropertyChanged != null)
       PropertyChanged(this, new PropertyChangedEventArgs(name));
   }
 }

_dgCars.AutoGenerateColumns = false;

DataGridViewTextBoxColumn makeColumn = new DataGridViewTextBoxColumn();
 makeColumn.DataPropertyName = "Make";
 makeColumn.HeaderText = "The Car's Make";

DataGridViewTextBoxColumn modelColumn = new DataGridViewTextBoxColumn();
 modelColumn.DataPropertyName = "Model";
 modelColumn.HeaderText = "The Car's Model";

DataGridViewTextBoxColumn yearColumn = new DataGridViewTextBoxColumn();
 yearColumn.DataPropertyName = "Year";
 yearColumn.HeaderText = "The Car's Year";

_dgCars.Columns.Add(makeColumn);
 _dgCars.Columns.Add(modelColumn);
 _dgCars.Columns.Add(yearColumn);

BindingList<Car> cars = new BindingList<Car>();

cars.Add(new Car("Ford", "Mustang", 1967));
 cars.Add(new Car("Shelby AC", "Cobra", 1965));
 cars.Add(new Car("Chevrolet", "Corvette Sting Ray", 1965));

_dgCars.DataSource = cars;

您需要在存储数据的对象上实现 INotifyPropertyChanged 接口。 如果值更改,每个属性都需要在属性的 set 调用期间引发该事件。 然后网格会自动获取更新。

一种简单的方法是使用 new BindingSource(object dataSource, "")

这将更新绑定源,从而更新表

例如:

dataGridView.DataSource = new BindingSource(phase3Results, "");

正如 Chris Gessler 和 Daniel 所建议的那样,您必须使用BindingList<>而不是 List<>,并且您的模型应该正确实现INotifyPropertyChanged 但更重要的是,检查您的模型是否实际上是一个 Class 当您的模型是 Records 或 Struct 时,Datagridview 将丢弃更改。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM