I am learning some WPF and have written this little program that reads an Excel file for data and updates the UI on save. Only after the first save does my ResetTimer() function work. But the GetDisplayData() does load the data and the program will update data on save. Only they timer does not start until that first save..
But I want the timer to start right away in case there is not a save event on the Excel file at load.
What can I do to get it to work, seems like whenever I try and place it in window_loaded or other places I tried, my program loops or does not load the data.
Thank you for your help.
using System;
using System.Data;
using System.IO;
using System.Windows;
using System.Windows.Threading;
namespace WPFReadExcel
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private const string ExcelPath = @"C:\";
private const string ExcelPathFile = @"C:\DataSource.xlsx";
DataTable _dashBoardData = new DataTable();
public MainWindow()
{
InitializeComponent();
}
protected void Window_Loaded(object sender, RoutedEventArgs e)
{
GetDisplayData();
StartFileSystemWatcher();
}
public void GetDisplayData()
{
var excelData = new ExcelData();
_dashBoardData = excelData.ReadExcelFile("Live", ExcelPathFile);
Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
{
ExcelDataGrid.ItemsSource = _dashBoardData.AsDataView();
RefreshDateTime.Content = "Refresh at: " +
DateTime.Now.ToShortTimeString();
}
));
}
private void ResetDisplayData()
{
if (_dashBoardData != null) _dashBoardData.Dispose();
GetDisplayData();
ResetTimer();
}
private void ResetTimer()
{
while (true)
{
System.Threading.Thread.Sleep(20000);
ResetDisplayData();
}
}
private void StartFileSystemWatcher()
{
if (string.IsNullOrWhiteSpace(ExcelPath))
return;
FileSystemWatcher watcher = new FileSystemWatcher();
// set directory to watch
watcher.Path = ExcelPath;
// set what to watch for
watcher.NotifyFilter = NotifyFilters.LastWrite;
// set event handlers
watcher.Changed += new FileSystemEventHandler(watcher_Changed);
// start watching
watcher.EnableRaisingEvents = true;
}
private void watcher_Changed(object sender, FileSystemEventArgs e)
{
ResetDisplayData();
}
private void Label_Loaded(object sender, RoutedEventArgs e)
{
RefreshDateTime.Content = "Refresh at: " + DateTime.Now.ToShortTimeString();
}
}
}