I have a C# Dialog based app. I want to save the preferences/settings the user choose, so that I could reload them in the next run.
I am new to C#, may be this is something quite basic but I do not know.
Do I have to explicitly write them to a file like ini or something ? or is there a built in way to do that.
The kind of config data is like checkboxes selelected, numericUpDOwn, checkedListbox - checked items etc
Select the control in the designer. Scroll all the way up in the Properties window and expand (ApplicationSettings). Click the indicated button to open a dialog. Select the property whose value should be persisted (like Checked for a check box) and click New in the dropdown.
Be a bit careful, not all properties are suitable to be persisted like this. An example is the form's Size. You don't want to store the size when the form is minimized or maximized, that size won't restore well. You need to do this by adding the setting in the Settings designer an only write it when the control is in the right state. In the case of Size, that's when the Resize event runs and the WindowState is Normal.
After you create the application settings as the other answers suggest, make sure you don't forget to call Properties.Settings.Default.Save(), for example:
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
Properties.Settings.Default.Save()
}
To Create a New Setting at Design Time
In Solution Explorer, expand the Properties node of your project.
In Solution Explorer, double-click the .settings file in which you want to add a new setting. The default name for this file is Settings.settings.
In the Settings designer, set the Name, Type, Scope, and Value for your setting. Each row represents a single settings
For more info you can refer here
You should use application settings. These will persist their values after you close your application, and you will be able to read from them when the program starts back up again.
Related
I'm having a strange issue that maybe being caused by my ignorance.
I have a treeview with an .AfterSelect and any time that i change the design of my form (in the deign view) the code gets removed for some reason.
here is my code
this.lstTreeView.AfterSelect += LstTreeView_AfterSelect; < this is the code that gets removed
this.lstTreeView.Location = new System.Drawing.Point(194, 56);
this.lstTreeView.Name = "lstTreeView";
this.lstTreeView.Size = new System.Drawing.Size(220, 498);
this.lstTreeView.TabIndex = 6;
this is the code that it allows to work.
private void LstTreeView_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
TreeNode CurrentNode = e.Node;
string fullpath = CurrentNode.FullPath;
MessageBox.Show(fullpath);
NrDirSearch(fullpath);
}
if anyone can give me some advice on why the .AfterSelect is being removed that would be really helpful.
I suggest you:
in the windows form designer, click the tree view to select it
in the properties grid click the lightning bolt and scroll to find the AfterSelect event
right click the name AfterSelect and choose reset
hit save all
Close out of the soution entirely/shut down visual studio
restart/reload the solution
Go back to the AfterSelect event as above, the box for which should be empty
click the drop down and choose your existing event handler
save all, quit and restart vs and check that the setting stayed
If you're finding it didn't stick, check that you don't have your designer open in another program e.g. A text editor that keeps autosaving an old version of the file that lacks the event handler?
Incidentally, the above process is how you add event in Design view - click the relevant control, lightning bolt, scroll to event wanted, double click the name of the event and you will be transported to your own code behind with a new named eventhandler created and ready to be filled
If you don't write any code in it, and go back to the designer and Reset the event as per the bulleted list instructions then your event handler method in your code will disappear. If you write code into the event handler then it is not removed when doing a reset, only empty handler methods are removed during reset
Side note: be careful with Undo if you see a message saying something like "performing this undo will cause a loss of work elsewhere" it usually indicates that the windows form design or designer.cs code will change as a result of actioning the undo
Designer files are safe to edit manually and it's sometimes necessary if the contents have gotten into a state where they are crashing the designer. I most often encounter this when deleting event handler s from my code that are still referenced in the designer. A screen appears saying a problem is preventing the forms designer from appearing, indicating the error line in the designer file. I have additionally in the past edited the designer directly to set large numbers of properties without the faff of using the designer - be mindful not to have a windows forms designer open at the same time as editing the designer.ca file because the forms designer will probably overwrite your changes. So long as you keep in mind that opening the same file in any two different editors at the same time can lead to conflict and loss of work, and take steps to ensure that edits in one editor are reflected in another before proceeding with further edits in the other editor, you'll be fine :)
Edit: having said that paragraph above, Mickey D made me realise an important point I'd overlooked:
The designer.cs file is read by the forms designer and uses to build the contents of the form, buttons, properties etc. As such if you are going to edit the designer.cs in a text editor you should limit your edits to only those things the forms designer can make use of, understand, represent and preserve when it next writes the file. Adding a line to set a button to enabled is fine. Removing a line that is causing it to crash is also good. Putting 27 methods that implement your entire program's database access strategy in is not a good idea as it will not be heeded or used to build the form when the designer reads the file and hence lost when the designer writes the file. If you're unsure of the difference between what will and won't be preserved stick to removing or fixing existing lines only rather than adding new lines of code
You should never[1] modify *.designer.cs files. They are code generated. Any changes you make are subject to being overwritten.
Instead either use the WinForms GUI Forms Designer to visually setup event handlers or you can do so in code in your form’s code-behind .cs file.
There are plenty of resources on the Net on how to use the WinForms designer.
[1] see Caius Jard's comment below for an exception to the rule that I concur with
Problem:
WPF application, no database.
It has main window, ribbon and there a button which opens new window, which has few checkboxes, textboxes which allows to set up parameteres how the job is gonna be done.
Now, how is the best way/best practice to store/save those parameteres and use them?
Settings class with properties and then creating global object when application starts? Then I could access this object in child window, save settings, then I could use such setting in MainWindow?
I guess it's a problem with OOP understanding.
Once I create Settings setting = new Settings(); in ChildWindow it is not accessible once window is closed.
But then, I've read somewhere to never set global objects and share them between windows.
Should I create Settings setting = new Settings() in MainWindow and then pass it in the constructor of ChildWindow? It could be like:
Settings setting = new Settings();
ChildWindow child = newChildWindow(setting);
Then in the new ChildWindow I could set up setting properties. As far as I know if you pass an object as a parameter it has reference to original object, so setting up properties in ChildWindow would affect MainWindow Settings object?
I know, the question is a bit messy, not sure if it's right place to ask such questions
If you just have a small number of fields to store, then using the built in User scoped Settings would be the easiest way. They are stored in XML files and each user will have their own settings file in a hidden data folder. You can set them up in a dialog window in Visual Studio and then refer to them simply in your code like this:
this.BackColor = Properties.Settings.Default.myColor;
Saving them is just as easy:
Properties.Settings.Default.Save();
These examples are from the following linked page... to find out full details, take a look at the Using Settings in C# page on MSDN.
I am writing a Settings form for one of my applications. Once the user clicks Tool > Settings a new form comes up with the settings that can be changed.
The TopMost property is set the True and working properly.
What I can't seem to find how to do is to keep the Form on focus. I do not want the use to be able to leave the form. The user has to close the form to continue using the application.
Thank you...
You are probably using Show() to show the settings form. Instead, use ShowDialog().
http://msdn.microsoft.com/en-us/library/c7ykbedk.aspx
Display it like this:
FormChild1 Child = new FormChild1();
Child.ShowDialog(this);
It's possible to bind a property to an existing application setting using the designer, that way I don't have to write something like
textBox.Text = Settings.Default.Name;
when initializing my form.
Now it looks like the binding stops there, ie if I change the value of my setting, it won't update the value in my textbox and vice versa.
Is it normal or am I missing something?
I'll explain how I do it on windows forms with Visual Studio 2010. It is likely similar in newer versions.
Click on the component to bind (textbox, checkbox, ...)
Make component's properties panel visible
Expand the node ApplicationSettings
Click the ... button to the right of (PropertyBinding)
Choose which setting you want the control bound to.
There is a more detailed tutorial at Exploring Secrets of Persistent Application Settings
Well, it depends.
First, I'm not sure if you're talking WPF or Windows Forms, so I'll assume neither.
Second, you are not "binding" anything. You are taking the value of Name and setting the property Text equal to this value. You are setting a property. This does not come with any magic side-effects which inextricably links the Name property to the Text property.
Third, you can change settings, but until you save them, they are not written back to your app.config. In a Windows Forms app, you'd have to do something like this:
// event handler for the Form.Closed event.
// this.FormClosed += FormClosed;
void FormClosed(object sender, FormClosedEventArgs e)
{
Settings.Default.Name = textBox.Text;
Settings.Default.Save();
}
In WPF, you'd use the normal binding semantics (which means you avoid the hassle of setting all the property values when closing), but you still have to trap for the form closing so you
can Save() the settings.
Binding:
<TextBox
xmlns:lol="clr-namespace:MyApplication.Settings"
Text="{Binding Name, Source={x:Static lol:Default}}" />
The Save() call happens much as with the Forms example, but you don't have to do anything other than call Save().
Where would you place the SaveSettings method in your project when the user is done editing any settings on the Settings dialog in your program?
Should it be in the return like:
using (frmSettings frmSettings = new frmSettings())
{
if (frmSettings.ShowDialog() == DialogResult.OK)
{
// clicked OK, should I call SaveSettings() here?
}
else
{
// clicked cancel.
}
}
Or where should I place it?
Putting the save code in the calling form is, in my opinion, putting it in the incorrect place. Yes, it will work in this instance, but it means that the settings form is not reusable, and that any error in your save code will cause the settings form to dismount before you know of any errors.
Additionally, if you add a new setting, you need to make the changes in two source locations, once to add controls (and initialize them) in the settings form, and once to save the values, in the calling form.
I'd attach the code to the OK button of the Settings form. If any errors are experienced in the saving, you can inform the user while their changes are visible and repairable. The form will be able to be called from different locations, as needed, or moved with nothing more than moving the ShowDialog() call. Your handling of DialogResult.OK should be used to update the calling form as the changes in settings apply to it.
// clicked OK, should I call SaveSettings() here?
That seems like a good place. =)
EDIT: I suppose it depends on the framework of the application, but there's nothing wrong with putting it there. It's a logical (by all definitions of logic) place to put it.
It depends on what the Form Settings is doing. If it just getting a user Okay or cancel then
// clicked OK, should I call SaveSettings() here?
is a good place.
However if you are getting setting information on the dialog form, then I would put the save logic in that form.
I definitely don't think there's anything logically wrong with putting the save function where you have suggested. Alternatively, in at least some cases, I believe it would be more appropriate to call the function to save settings within the Settings form; but that depends a lot on the overall architecture of your application.
If frmSettings form has the settings you need to save, I would store the settings from within that form -and in Isolated Storage or external XML file depending on your design.