How can I store the user's choice permanently in c# winform.
I wrote this code to fetch the setting:
string my_data_to_do = (string)Settings.Default["MyDataToDo"];
And to save the user's setting I wrote:
if (checkBox3.Checked)
{
Settings.Default["MyDataToDo"] = "Tasks In Hand";
}
else
{
Settings.Default["MyDataToDo"] = "Nothing To Do";
}
This is showing the saved data but only until I exit my application. When I exit and start my program again, all these settings gets automatically removed, and the default data comes, which I saved in Settings.settings file.
Can anyone please help me in this?
It's hard to tell if you're doing it from just the code exert you've posted, but after setting the setting like that you will need to call Settings.Default.Save() to have it persist beyond the application closing.
Related
I have a checkbox(Name:tarahi_algouritm) and a button(Name:button1) on my form(Name:frm_choose).I want to save the latest changes on my checkbox as user clicked on the button.it means user run the program and check the checkbox and then click on button and then close the program.when he/she Rerun it,checkbox should be checked.or someway he disable the checkbox and click on button and after another run,checkbox should be disabled.
for this, in application setting(table part) put a checkbox (Name:s_tarahi_algouritm)and choose USER in scope part..as I said changes are apply on checkbox and s_tarahi_algouritm is used for save the latest changes on checkbox.I wrote these codes:
private void frm_choose_Load(object sender, EventArgs e)
{
if (Properties.Settings.Default.s_tarahi_algouritm!=null)
tarahi_algouritm= Properties.Settings.Default.s_tarahi_algouritm;
}
private void button1_Click(object sender, EventArgs e)
{
Properties.Settings.Default.s_tarahi_algouritm = tarahi_algouritm;
Properties.Settings.Default.Save();
}
but When I make changes on checkbox and close the debug and Rerun it,changes are not applied.
what should I do?where is wrong?I am partly beginner so explain explicit.
thank you all
The problem is the settings files are written out in two parts: one to the application settings (which you can't save to) and the other to the user settings (which you can save to). You need to save the user settings (it gets written to your c:\users{userid}... directory).
Look at the most up-voted response to Farzin's link. It explains the issue as well.
Here's a more thorough explanation: App.config: User vs Application Scope
Here's an example.
I created a webform app and added a Settings file to it (called TestSettings.settings). I added two values:
When you run this application it creates a file in the application directory named the same as your executable with .config appended that contains (among other things) a element and a element. But this file only contains the initial values. If you change the value under the element and call Save() it will not update this file. It will create a file:
c:\Users{username}\AppData\Local{appname}{random_dir_name}{version}\user.config
My code to demonstrate this was:
Console.WriteLine(TestSettings.Default["UserValue"]);
TestSettings.Default["UserValue"] = "def";
TestSettings.Default.Save();
I tested many things like:
Properties.Settings.Default.Properties.Add(new System.Configuration.SettingsProperty("a"));
Properties.Settings.Default.Properties["a"].DefaultValue = "b";
Properties.Settings.Default.Save();
it has not error but do not save. In this link:
C# Settings.Default.Save() not saving?
Answered you must add Properties.Settings.Default.Reload(); after saving, I did that but not changed. It seems no one knows the answer.(I read many articles).
It looks like a cancer to me! I suggest you to easily save your settings to a xml file.
Below i add an easy xml saving method:
using System.Xml.Linq;
And
XElement settings;
try
{
settings = XElement.Load("settings.xml"); //beside the app .exe file
}
catch (Exception) // it is first time and you have not file yet.
{
settings = new XElement("settings");
settings.Save("settings.xml");
}
If you want to add new element:
settings.Add(new XElement("firstKey", tarahi_algouritm.Checked.ToString()));
settings.Save("settings.xml");
If you want to read or edit element:
XElement settings = XElement.Load("settings.xml");
string firstKey = settings.Element("firstKey").Value; //reading value
settings.Element("firstKey").Value = "New Value"; //Edit
settings.Save("settings.xml"); //Save
Remember that firstKey is only a name and you can use another names instead.
Here is my timer enabled/disabled code:
{
if (checkboxConsoleStats.Checked == true)
{
frmMain.frmObj.consoleStatTimer.Enabled = true;
}
else if (!checkboxConsoleStats.Checked == false)
{
frmMain.frmObj.consoleStatTimer.Enabled = false;
}
I want to make the form remember the 'Checked' value after termination of the form and the application, sorry this is vague, I am in a rush. Thanks.
If you need to store the value after full termination of the app - you'll have to use a persistent storage that the app can access on init.
The easiest would be to use a flat file (just store a flag), but if you believe you will have more values that you'll need to remember - consider using XML/JSON file that you parse upon init and write to upon termination.
If you have more dynamic data (that needs to be written and read while the app is running) - you should consider using a DB. For a small app you can use an embedded DB such as SQLITE. Easy to use and needs no installation for the end-user.
How can I get the number of times a program has previously run in c# without keeping a file and tallying. Is there a Application class or something in c# to check the count.
Please give a detailed explantion as i know nothing about it.This is A windows console application not windows forms.
You can do that my creating an Entry in the Registry. And another way is by using an Application Settings.
But I prefer Application Settings because it has less task to do.
See HERE: Creating an Application Settings.
Tutorial From Youtube
Recent versions of Windows automatically maintain this information in the registry under HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist.
The data is obfuscated with ROT13, but that's easy to "decrypt". A free utility (with source code) is available and can serve as your starting point.
You could send a message to a database or webservice every time the program starts up (assuming there's a network connection).
You could keep a count on some form of hardware thet's not a standard storage device (therefore not technically being a file).
You could make a registry entry that you keep the count in (if you ignore the fact that the registry entry is, at some level, persisted into a file somewhere).
You could just have a file somewhere that keeps track of the count. Not sure why you're so opposed to this one in the first place....
If you are running a Winforms application, the you can easily use the Application Settings. Right click on your Solution Name --> Properties --> Settings Tab. More info and tutorial here.
Then, every time your program starts, increment this setting and save it.
Ref: Count the number of times the Program has been launched
In my knowledge Windows does not keep this information for you. You would have to tally the value somewhere (file, database, registry setting).
Better way is Application Settings as:
Create setting in app.config and then use it as:
Properties.Settings.Default.FirstUserSetting = "abc";
then, you usually do this in the Closing event handler of the main form. The following statement to Save settings method.
Properties.Settings.Default.Save();
Implementation using Registry:
static string AppRegyPath = "Software\\Cheeso\\ApplicationName";
static string rvn_Runs = "Runs";
private Microsoft.Win32.RegistryKey _appCuKey;
public Microsoft.Win32.RegistryKey AppCuKey
{
get
{
if (_appCuKey == null)
{
_appCuKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(AppRegyPath, true);
if (_appCuKey == null)
_appCuKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(AppRegyPath);
}
return _appCuKey;
}
set { _appCuKey = null; }
}
public int UpdateRunCount()
{
int x = (Int32)AppCuKey.GetValue(rvn_Runs, 0);
x++;
AppCuKey.SetValue(rvn_Runs, x);
return x;
}
If it's a WinForms app, you can hook the Form's OnClosing event to run UpdateCount.
Then Check tutorial to Read, write and delete from registry with C#
I am trying to get user confirmation from c# code behind file, to confirm if user wants to overwrite the existing file on server of cancel the operation but so far no luck.
this is my code :
if (File.Exists(filePath))
{
string alertMsg = #"confirm('A File already exists with the same name. \n Would you like to overwrite the existing file ?');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "Test", alertMsg, true);
}
else
{
fuPSD.SaveAs(filePath);
}
any help would be highly appreciated.
That code will pop up the message if the file exists and save it if it doesn't.
But you will need to take some action on the confirm dialog result on the client side and either trigger a postback or some other server call to perform the operation in the case of the override.
The problem is that your JavaScript registration will ask the user to confirm to overwrite the file after the next page loads. This then poses the issue of telling whether the user confirmed or denied from the server since you're confirm with be client side.
In the past I've used a hidden field to toggle true/false to show a popup from the server side. This gives me the ability to wire up the events to a delegate on the code behind(I.e make my own confirm box with my own buttons). You can still do this without it by I found that it leads to a lot of messy and hard to follow script like callin __doPostback manually.
something like this :
create
<asp:hiddenField id="hf" />* in the aspx file
also put on the JS location a Declaration :
var answer=null;
back to server :
string alertMsg = #"if (confirm('A File already exists with the same name. \n Would you like to overwrite the existing file ?')==true) answer='1'; else answer='0';";
now on the server side :
read :
hf.value
I've written a class that should allow me to easily read and write values in app settings:
public static class SettingsManager
{
public static string ComplexValidationsString
{
get { return (string)Properties.Settings.Default["ComplexValidations"]; }
set
{
Properties.Settings.Default["ComplexValidations"] = value;
Properties.Settings.Default.Save();
}
}
the problem is the value isn't really saved, I mean it is not changed when I exit the application and run it again. What can I do to ensure that the saved value persists between closing and opening again?
settings scope must be user not application
You should check
Properties.Settings.Default.Properties["ComplexValidations"].IsReadOnly
It is probably true, this is what Roland means with "Application Scope". Save will fail silently. Take a look at Project|Properties|Settings, 3rd column.
Are you sure it's not saving the changes? The [ProgramName].exe.config file in the bin folder won't be updated. The acutal file used is usually put in C:\Documents and Settings\[user]\Local Settings\Application Data\[company name]\[application].exe[hash string]\[version]\user.config. I know when I tried this kind of thing it took me a while to realise this was the file that was getting updated.
I just tested a User Setting and it is persisted if you run this Console app twice:
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Settings1.Default.Setting);
Console.ReadLine();
Settings1.Default.Setting = "A value different from app.config's";
Settings1.Default.Save();
}
}
Just try it out. It won't take a minute.