简体   繁体   English

如何在 WPF 中刷新数据网格

[英]How to refresh datagrid in WPF

My source is in a MySQL database, I've made an update command and now I need to refresh my DataGrid .我的源代码在 MySQL 数据库中,我已经执行了更新命令,现在我需要刷新我的DataGrid

MySqlCommand cmd = new MySqlCommand(
  "update request set status = " + StatusRequest(value) + 
  " where id = " + rowView[0].ToString() + "", conn);
MySqlDataReader myReader = cmd.ExecuteReader();

How do I refresh my DataGrid ?如何刷新我的DataGrid

Try mydatagrid.Items.Refresh()试试mydatagrid.Items.Refresh()

Reload the datasource of your grid after the update更新后重新加载网格的数据源

myGrid.ItemsSource = null;
myGrid.ItemsSource = myDataSource;

FromMSDN -来自MSDN -

CollectionViewSource.GetDefaultView(myGrid.ItemsSource).Refresh();

Bind you Datagrid to an ObservableCollection , and update your collection instead.将您的 Datagrid 绑定到ObservableCollection ,然后更新您的集合。

How about怎么样

mydatagrid.UpdateLayout();

I had a lot of trouble with this and this is what helped me get the DataGrid reloaded with the new values.我在这方面遇到了很多麻烦,这就是帮助我用新值重新加载 DataGrid 的原因。 Make sure you use the data type that your are getting the data from to get the latest data values.确保使用从中获取数据的数据类型来获取最新的数据值。

I represented that with SomeDataType below.我在下面用SomeDataType表示。

DataContext.Refresh(RefreshMode.OverwriteCurrentValues, DataContext.SomeDataType);

Hope this helps someone with the same issues I had.希望这可以帮助遇到与我相同问题的人。

If you want update single row:如果要更新单行:

Create new ObservableCollection and initialize it创建新的 ObservableCollection 并初始化它

public ObservableCollection<myModel> myObservableCollection { get; set; } = new ObservableCollection<myModel>();

Update row更新行

//Get current row as your model
var row = myDataGrid.CurrentItem as myModel;
//Find in your collection index of selected row
var b = myObservableCollection.IndexOf(myObservableCollection.FirstOrDefault(e=>e.Id == row.Id));
//Create a copy of this row
var k = row.Clone() as myModel;
//Here you can mofidy what you want
k.Name = "New name";
k.SomethingId = 2137;
//Replace object in you collection
myObservableCollection[b] = k;

Here's code to clone your model这是克隆模型的代码

public object Clone()
{
    return this.MemberwiseClone();
}

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

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