簡體   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