0

I am creating a windows forms application which reads bunch of tags from several xml files and writes the data to the DataGridview in win forms. Currently, the data is showing on the DataGrid, but if I change any of the xml files, it is not updating the data in the dataGridView. The requirement is the data must automatically change in the dataGridView without any manual intervention, if any changes are done in the xml files. I tried searching online but couldn't find any answers to solve this problem

Please let me know if anybody has resolved this issue.

marak
  • 260
  • 3
  • 19
  • You need [file watcher](https://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(v=vs.110).aspx). – bokibeg Mar 14 '15 at 21:16
  • I agree with bokibeg. And I don't know what kind of a data structrue you're binding to, but you might consider using a [BindingSource](https://msdn.microsoft.com/en-us/library/system.windows.forms.bindingsource%28v=vs.110%29.aspx) if you want the DataGridView to get notifications. – Mark Waterman Mar 14 '15 at 21:24
  • Thank you I am using FileWatcher, I am able to monitor my folder for any changes in the files. I am using Dictionary and filling the dataosource with myobject values. How should I use bindingSource to send notifications to DataGridView? – marak Mar 14 '15 at 22:08

1 Answers1

0

A dictionary isn't a great candidate for binding--the Dictionary's ValueCollection<T> doesn't support IList, so it's not a very good match for a BindingSource. If you're stuck with a Dictionary then the always authoritative Marc Gravell has a solution here that may work for you.

If you don't have to use a dictionary then the typical, somewhat naïve approach is to set the BindingSource.DataSource to a List<MyObject>, and then set the DataGridView.DataSource to that BindingSource. Once you have that set up, instead of adding/removing items through through the underlying List, you add/remove them through the BindingSource's add/remove methods--the UI will pick up those changes. If you change an existing item then you can call BindingSource.ResetItem method to notify the UI that it needs to refresh that item.

But the best, most flexible approach would be to set your DataGridView.DataSource property to a BindingList<MyObject>, and, ideally, have your MyObject class implement INotifyPropertyChanged... the BindingList notifies the UI of new items, and the INotifyPropertyChanged implementation notifies the UI about changes to existing items. This lets you modify the collection directly without having to worry about keeping the UI in sync.

Community
  • 1
  • 1
Mark Waterman
  • 961
  • 7
  • 16
  • Thank you everyone for your help. Replaced Dictionary with a bindingList and solved it. Also made use of FileSystemWatcher class to monitor the files I needed. – marak Mar 15 '15 at 23:08