I’m storing a whole bunch of settings for my winforms program in various .settings files.
Included in these settings are System.Drawing.Point, System.Drawing.Location, System.TimeSpan, System.DateTime, etc…
When I bind a form’s Location to a System.Drawing.Location, and call the .Save() method, it all seems to work fine. That is, since there doesn’t seem to be a need for a cast, the form’s System.Drawing.Location is directly compatible with the System.Drawing.Location setting stored in the .settings file.
Additionally, if I say TimeSpan timeSpan = Settings.Duration; that also works fine.
Now, I have made a large settings form, where the user can adjust various parameters, including the various DateTime and TimeSpan settings. These are visible and editable in many TextBox, which I have data bound in the following way:
Settings DefaultSettings = Settings.Default;
TextBox1.DataBindings.Add(("Text", DefaultSettings, "Duration", false, DataSourceUpdateMode.OnValidation, new TimeSpan(00, 30, 00));
The TimeSpan is visible in the TextBox, however when I try to edit it and call Save() on the settings data source, I get the following error:
Value of ‘0’ is not valid for ‘Value’. ‘Value’ should be between ‘Minimum’ and ‘Maximum’.
Parameter name: Value
The error originates from the Visual Studio generated code block:
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("00:30:00")]
public global::System.TimeSpan StartWorkDay {
get {
return ((global::System.TimeSpan)(this["Duration"]));
}
set {
this["Duration"] = value;
}
}
I think the problem is caused by the fact that it’s trying to turn a string into a System.TimeSpan, and the various other classes I have in my .settings file.
Since I’m binding them using the DataBindings.Add( which accepts strings for the parameters, I can’t cast or use the new keyword there.
I could handle it all manually in code: updating the settings file by constructing the objects parameter-by-parameter, but I have so many settings stored in so many TextBoxes and NumericUpDowns that I would prefer to just bind them straight to the TextBox, assuming that’s possible.
What is the easiest way I can achieve this?
I tried the following code in a sample windows form application and it did the save without any exceptions.
Hope it helps.