Skip to content

Iterating through a resource file

Sam

Asked Oct 14, 2010, 12:06 AM EDTSolved
Share
LinkedInX
Hi,
I have a number NumericUpDown controls that I wish to save their settings.
I create a resource file and save them by foreach loop with Type (NumericUpDown) condition.
I then iterate through the file to read back and set the values into the controls.
Unfortunately, I am probably doing something wrong, as I do not get the values back into the controls.
1. The resource file is written, and looks OK (Using a hex editor).
2. Saving and reading the resource file manually (one-by-one, no foreach) works OK.
3. Seems as if the issue is with reading and loading into the controls.
Can someone help me out?
Thanks, Sam
Here is a simplified stripped code example :
(To run, build a form with 3 generic numericUpDown (1,2,3) controls and two buttons: buttonSave and buttonLoad)
 
C#
using System.Windows.Forms;
using System.Resources;
using System.Collections;
namespace ResourceFile
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void saveToFile()
{
ResourceWriter rw = new ResourceWriter(@"C:\Temp\MyFile.resources");
foreach (Control resource in Controls)
{
if (resource.GetType() == typeof(NumericUpDown))
{
rw.AddResource(resource.Name, resource.Text);
}
}
rw.Generate();
rw.Close();
}
 
private void loadFromFile()
{
ResourceSet rs = new ResourceSet(@"C:\Temp\MyFile.resources");
foreach (DictionaryEntry resource in rs)
{
rs.GetObject(resource.Key.ToString());
}
rs.Close();
}
private void buttonSave_Click(object sender, System.EventArgs e)
{
saveToFile();
}
private void buttonLoad_Click(object sender, System.EventArgs e)
{
loadFromFile();
}
}
}

2 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • ✓ Accepted answer0
    I couldn't see the code to load the control values.
    private void loadFromFile() {
    ResourceSet rs = new ResourceSet(@"C:\Temp\MyFile.resources");
    foreach (DictionaryEntry resource in rs)
    {
    foreach (Control ctrl in Controls)
    {
    if (ctrl.Name.ToLower() == resource.Key.ToString().ToLower() && ctrl.GetType() == typeof(NumericUpDown))
    {
    var value = rs.GetObject(resource.Key.ToString());
    ((NumericUpDown)ctrl).Value = Convert.ToDecimal(value);
    }
    }
    }
    rs.Close();
    }
    Hope this help you.
    0
  • 0
    Thanks Murali once again.
    It works perfectly and I use it as is, but I still need to investigate and to understand why is the double iteration required.
    I tought there should be a simple one-iteration to extract.
    It looks as if you use one loop to extract the value from the table, the other one to load it into the NumUpDown.
    Am I right?
    Once again, a prompt and correct reply.
    Sam
    P.S.
    There was no code to load, just the comment:
    (To run, build a form with 3 generic numericUpDown (1,2,3) controls and two buttons: buttonSave and buttonLoad)
    0