Skip to content

Instantly share code, notes, and snippets.

@amenayach
Last active April 12, 2018 23:27
Show Gist options
  • Save amenayach/0d4cf66de7fae736cdf294da84eb6955 to your computer and use it in GitHub Desktop.
Save amenayach/0d4cf66de7fae736cdf294da84eb6955 to your computer and use it in GitHub Desktop.
This helps to maintain last used inputs in a winform, let's say you have a Title and Description text boxes in a form F, this class will ensure when the form F is loaded that last entered input in these text boxes will be present at load event
namespace System.Windows.Forms
{
//This class requires JSON.net package, to install from the nuget console use:
//Install-Package Newtonsoft.Json
using Newtonsoft.Json.Linq;
using System.IO;
using System.Linq;
public static class StickyInput
{
private const string Filename = "appsettings.json";
public static void Stick(this Form form, params Control[] controls)
{
if (form != null && (controls?.Any() ?? false))
{
form.Load += (sender, e) =>
{
var json = GetAppSettings();
var formEntry = (json[form.Name] as JObject) ?? new JObject();
foreach (var control in controls)
{
control.Text = formEntry[control.Name]?.ToString();
}
};
form.FormClosing += (sender, e) =>
{
var formEntry = new JObject();
foreach (var control in controls)
{
formEntry[control.Name] = control.Text;
}
SaveAppSettings(form.Name, formEntry);
};
}
}
private static JObject GetAppSettings()
{
var jsonFilename = Path.Combine(Directory.GetCurrentDirectory(), Filename);
if (!File.Exists(jsonFilename))
{
return new JObject();
}
return JObject.Parse(File.ReadAllText(jsonFilename));
}
private static void SaveAppSettings(string entry, JObject json)
{
var jsonSettings = GetAppSettings();
jsonSettings[entry] = json;
var jsonFilename = Path.Combine(Directory.GetCurrentDirectory(), Filename);
File.WriteAllText(jsonFilename, jsonSettings.ToString());
}
}
}
@amenayach
Copy link
Author

Usage

In the targeted form constructor:

public SomeForm()
{
  // If tbTitle and tbDescription are 2 text boxes
  this.Stick(tbTitle, tbDescription);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment