I have a Form that gets the name of one of its Labels from a text file. This works fine when starting the app. But from another Form that text file changes and I would like that Label to change accordingly. This refresh takes place when the Form that made those text files changes took place closes. I thought Refreshing it would do the same thing as what happens when I use the MainForm_Load. But I guess not. Could I be doing something wrong or just misunderstand what Refresh does? Thanks
Your post is a bit confusing, but try MainForm.Invalidate(true) instead of MainForm.Refresh()...
The Refresh
method only calls the Invalidate
method, so it just causes a repaint of the controls with their current data.
Put the code that gets the data from the text file in a separate method, so that you can call it both from the Load
event handler, and from any code that needs to cause the reload.
As far as I am aware Form.Load is raised once when an instance of the form is created. In order for the logic that is updating the label to re-execute it must be called from somewhere else whenever the label has been updated
One possibility is to refactor the label update code into a method and then use a FileSystemWatcher to receive an event when the contents of the file changes and then execute the update method in response
All the Refresh method on a form does is Invalidate the form then calls Update (which boils down to a UpdateWindow call)
One way to solve your problem is to use the FileSystemWatcher object to monitor your text file for changes. When a change is detected, it can then call your code that opens the file and outputs the data to your label.
FileSystemWatcher fsw = new FileSystemWatcher();
fsw.Path = @"c:\temp"; // path to file
fsw.Filter = "yourfile.txt";
fsw.Changed += fsw_Changed;
fsw.EnableRaisingEvents = true;
Then in your changed event you just defined
void fsw_Changed(object sender, FileSystemEventArgs e)
{
updateLabelFromTextFile();
}
private void updateLabelFromTextFile()
{
var fs = File.OpenText(@"c:\temp\yourfile.txt");
string sContent = fs.ReadToEnd();
fs.Close();
fs.Dispose();
if (label1.InvokeRequired)
{
MethodInvoker mi = delegate { label1.Text = sContent; };
this.BeginInvoke(mi);
}
else
label1.Text = sContent;
}
Note that FileSystemWatcher events are fired in a separate thread, thus the need for the BeginInvoke.
Here is a link to an example (just do a search on FileSystemWatcher and you'll find tons more examples).