Saving form settings on exit - c#

I am trying to have my application save some form settings on exit.
Eg. I have a textbox and a checkbox and I want to save the states of both to a settings file.
I already know how to save the settings to the settings file, the trouble is that the settings don't save in the exiting method.
My application exit method is this:
void OnApplicationExit(object sender, EventArgs e)
{
MessageBox.Show("Exiting...");
session.Default.Path = txtPath.Text;
session.Default.Regex = chkRegex.Checked;
}
These are the two ways I've tried to have it call on exit:
private void Form1_Load(object sender, EventArgs e)
{
AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnApplicationExit);
}
And
private void Form1_Load(object sender, EventArgs e)
{
this.FormClosing += OnApplicationExit;
}
With both, the method gets called, the message box is shown but neither save the settings. I think the form controls are getting unloaded before it has a chance to read the values.
How can I save these form control values on exit?

If this is what i think it is, then this might be relevant
How To: Write User Settings at Run Time with C#
Settings that are application-scoped are read-only, and can only be
changed at design time or by altering the .config file in between
application sessions. Settings that are user-scoped, however, can be
written at run time just as you would change any property value. The
new value persists for the duration of the application session. You
can persist the changes to the settings between application sessions
by calling the Save method.
So likely, you could just call
session.Default.Save();
Note : I could be completely wrong

Related

How to check from the beginning in Windows Forms App

_Changed events check it if it is changed. How can I check it from the beginning.
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
if (dateTimePicker1.Value.Month == 2)
{
pictureBox1.Visible = true;
}
else
{
pictureBox1.Visible = false;
}
}
You can call the event handler from the constructor, or sometimes better, the Load of the form:
private void MyForm_Load(object sender, EventArgs e)
{
dateTimePicker1_ValueChanged(dateTimePicker1, EventArgs.Empty);
}
There is also the Shown event called after the window first appears on the desktop.
Thus the control will be initialized as expected.
Here is the chain of calls:
Constructor : prefered place to instantiate objects and initialize UI instances.
Load : prefered place to create and initialize non designer UI objects or complete them like populating combobox or dataset.
Activated : prefered place to do things each time the form is activated and get focus.
Shown : prefered place to do things after the form is showned like open another form or show a info box.
The difference between using constructor, load or shown is mainly to have a clean code design and a smooth UI behavior.
There is no real difference between putting code in the constructor or in the load, else the reference and window handle are created.
Order of Events in Windows Forms (MS Doc)

How to persist from build programmatically?

I want to be able to load some information programmatically into Properties.Settings.Default before I publish it, but it doesn't persist. How do I overcome that?
I have (as a test):
private void button1_Click(object sender, EventArgs e)
{
Properties.Settings.Default.Setting1 = "abc";
Properties.Settings.Default.Save();
}
private void button2_Click(object sender, EventArgs e)
{
Text = Properties.Settings.Default.Setting1;
}
I clicked on button1, then published (with clickonce) and then run the published application and clicked on button2. The Text was empty.
If don't publish the application, rather just close it and reopen it and click on button2 – I get "abc".
See the following post http://www.codeproject.com/Articles/17659/How-To-Use-the-Settings-Class-in-C
publishing won't click the button for you.
You need to detect the setting isn't initialised correctly (compare with an application setting perhaps) and then set and save it yourself.
Blank / doesn't exist / = somesettingToUpgrade
and a little routine to find a setting by name, set and save then you could put that in the button click handler as well as say FormLoad.
It seems that the problem was that the scope was "user". But if the scope is "application" – it can't be changed programmatically.
So there seems not to be a way to do it. Persist from build programmatically, that is.

When inserting with tableadapter in one form, how to refresh data in another?

Visual Studio 2010 Express, Windows Forms.
Have made myself my first little application which used a local database (a journal app).
First form (which load when app starts) shows every entry that has been made.
A "Add button" show up a new form, from where I can add a new entry.
Now, everything works this far.
But when I close the add form, after adding a new entry, the new entry isn't displayed in the first form. I have to close the program and start it up again the see the new entry.
How can I refresh the data in the first form, when the add form closes?
Best regards from Denmark
First of all you must open your second form as dialog like new FormAdd().ShowDialog(this);
this will stop the code until FormAdd close, then you can reload the data as you load in form firs load.
your code will be like this
private void Form1_Load(object sender, EventArgs e)
{
LoadData();
}
private void btnAdd_Click(object sender, EventArgs e)
{
new FormAdd().ShowDialog();
LoadData();
}
private void LoadData()
{
//load your data
}
by the way you can use DialogResult for unnecessary prevent refreshs is user does not insert a record to db. in FormAdd code set DialogResult value and in main form use like this
private void btnAdd_Click(object sender, EventArgs e)
{
if (new FormAdd().ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
LoadData();
}
I'm aware that this is an old post, but in looking for an answer on this site to the same situation, I also discovered another method which, may work as well.
I also have Visual Studio 2010 Express, Windows Forms. I invoke a separate form via a MenuStrip button click. Using this 2nd form, I add various hours-of-the-day to a dataGridView on my main form, i.e., 9:00AM, 9:30AM etc.
I found that after adding a new time, when I clicked a combobox dropdown button on my dataGridView that, the new entry was not there. Like the original poster, I would have to close and reopen my main form.
In my Form_Load event, VS had added a TableAdapter entry, which loads data into the table, i.e.
this.TimesTableAdapter.Fill(this.AssignmentsDataSet.Times);
However, by copying this line into the form's Form__Activated event, when I click on the dataGridView's dropdown list, the newly created entry now appears.
Hopefully, this proves useful to any who run into the same issue.

checking if form data has been changed

I have been trying the following C# code to check if form data has been changed before closing and saving but it seems that it always reports the form as being changed even when no changes were made.
//Declare a private variable
private bool requiresSaving =false;
//Declare an event
private void SomethingChanged(object sender, EventArgs e)
{
requiresSaving = true;
}
//Hook up this event to the various changed events, eg
this.txtNameDepart.TextChanged += new System.EventHandler(this.SomethingChanged);
//Check this variable when you are closing the form
private void DepartamentEdit_FormClosing(object sender, FormClosingEventArgs e)
{
if (requiresSaving)
{
....
You also need to set requiresSaving false in the saveDepart method.
I think you hook up these events even before you load your initial data. Then SomethingChanged fires and enable the save button even the user doesn't change anything.
You could either unhook these events when loading the default/existing data or hook up these events after loading default/existing data.
//Un-Hook when loading your default/existing data.
private void SetDefaultData()
{
this.txtNameDepart.TextChanged -= new System.EventHandler(this.SomethingChanged);
this.txtNameDepart = "My default text";
this.txtNameDepart.TextChanged += new System.EventHandler(this.SomethingChanged);
}
you should show all the places where you set the flag to true, just in case.
also this code:
//Hook up this event to the various changed events, eg
this.txtNameDepart.TextChanged += new System.EventHandler(this.SomethingChanged)
even understanding what you are trying to do, I think this is bad because if you have many controls and soon or later you will handle the logic of each change event with some more specific code for the individual controls, you should not attach the same event handler to all of them at once.
if all your controls are bound to a BindingSource you could use another approach.
if your controls are populated manually by you with some assignment from a business object on form load, you could also imagine to compare such object's properties with the original one (if you also saved a copy of the original of course) in the form_closing.

System Tray Icon

Okay firstly I just started C# so I'm not exactly the most skilled programmer out there. Okay so here's my problem that may seem stupid to you guys ;)
I have a simple enough app that a friend asked me to do. So far I have managed with a bit of Google but I'm stuck with this. The app runs fine and minimizes to the system tray and maximizes from the system tray which is good. However, when I open a second form from that application it creates another icon in the system tray and starts duplicating every time I open another form. So eventually I have lots of icons and all of them are seperate instances of the main form. System Tray events
private void notifyIcon_systemTray_MouseDoubleClick(object sender, MouseEventArgs e)
{
if (FormWindowState.Minimized == WindowState)
{
Show();
WindowState = FormWindowState.Normal;
}
}
private void CronNecessityForm_Resize(object sender, EventArgs e)
{
notifyIcon_systemTray.Visible = true;
if (FormWindowState.Minimized == WindowState)
Hide();
}
private void restoreContextMenuItem_Click(object sender, EventArgs e)
{
Show();
WindowState = FormWindowState.Normal;
}
To open the Form:
private void preferencesToolStripMenuItem_Click(object sender, EventArgs e)
{
CronPreferences.formPreferences CronPreferences = new CronPreferences.formPreferences();
CronPreferences.Show();
}
Close it:
private void button2_Click(object sender, EventArgs e)
{
this.Hide();
}
How can I have all Forms map to the same icon in the System Tray?
You will need a single global tray icon that they all access. Do this by using a static variable that stays the same throughout different instances of the class.
Then, if you want to:
Open one form: keep a reference to the latest form in a variable and open it.
Open all minimised forms: iterate through each form and open them again.
If I got it right, you want to keep only a single instance of your application running. In that case, your title is a bit misleading since your problem has nothing to do with tray icons or multiple forms.
Code Project: A Single Instance Application which Minimizes to the System Tray when Closed
On the other hand, if you really have a main form in your app, which opens the second form (which creates a tray icon), in that case you simply need to make sure your second form is instantiated only once:
public class MainForm
{
private SecondForm _secondForm;
public void OpenSecondForm()
{
// create it only once
if (_secondForm == null)
_secondForm = new SecondForm();
// otherwise just show it
_secondForm.Show();
}
}

Categories