MS Access and VB has Tag property for form and control where you can store at runtime and persist with the app. Is there something equivalent in .NET ?
+2
A:
Most of the UI controls in .NET do have a .Tag
property that can be used for the same purpose.
However, if you need additional functionality, you can make a class which inherits from the base control (i.e. you could make a class called SpecialPictureBox that inherits from PictureBox and adds additional fields), and use it in your Windows Forms just as you could use a PictureBox.
routeNpingme
2009-08-10 20:41:04
Unless I'm mistaken, .Tag is not persisted
Eric J.
2009-08-10 20:46:42
.Tag isn't persisted across VB6 either. ;)
routeNpingme
2009-08-11 03:06:46
+1
A:
There is a Tag property in Windows Forms, but it is not persisted.
The pattern I use is to create a class called Preferences (has properties for each piece of information I want to persist), which is then managed with a PreferencesManager class like this one:
public class PreferencesManager
{
static private string dataPath = null;
static public string DataPath
{
get
{
if (dataPath == null)
{
string baseFolder = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
dataPath = Path.Combine(baseFolder, @"MY_APP_NAME");
if (!Directory.Exists(dataPath))
{
Directory.CreateDirectory(dataPath);
}
}
return dataPath;
}
}
/// <summary>
/// Saves the specified preferences.
/// </summary>
/// <param name="pref">The preferences.</param>
static public void Save(Preferences pref)
{
// Create file to save the data to
string fn = "Preferences.xml";
string path = Path.Combine(DataPath, fn);
using (FileStream fs = new FileStream(path, FileMode.Create))
{
// Create an XmlSerializer object to perform the serialization
XmlSerializer xs = new XmlSerializer(typeof(Preferences));
// Use the XmlSerializer object to serialize the data to the file
xs.Serialize(fs, pref);
}
}
static public Preferences Load()
{
Preferences ret = null;
string path = string.Empty;
try
{
// Open file to read the data from
string fn = "Preferences.xml";
path = Path.Combine(DataPath, fn);
using (FileStream fs = new FileStream(path, FileMode.Open))
{
// Create an XmlSerializer object to perform the deserialization
XmlSerializer xs = new XmlSerializer(typeof(Preferences));
// Use the XmlSerializer object to deserialize the data from the file
ret = (Preferences)xs.Deserialize(fs);
}
}
catch (System.IO.DirectoryNotFoundException)
{
throw new Exception("Could not find the data directory '" + DataPath + "'");
}
catch (InvalidOperationException)
{
return new Preferences();
}
catch (System.IO.FileNotFoundException)
{
return new Preferences();
}
return ret;
}
}
Eric J.
2009-08-10 20:45:34