1

I have a folder browser button and a combobox which shows selected path. I want it keep previously selected paths. I wrote this code and it works fine. But I wanna know if there is more efficient way to do this.

      private void Form1_Load_1(object sender, EventArgs e)
       string hurrem, hurrem2, hurrem3, hurrem4, hurrem5;
        hurrem = Settings.Default["com1"].ToString();
        hurrem2 = Settings.Default["com2"].ToString();
        hurrem3 = Settings.Default["com3"].ToString();
        hurrem4 = Settings.Default["com4"].ToString();
        hurrem5 = Settings.Default["com5"].ToString();


        comboBox2.Items.Add(hurrem);
        comboBox2.Items.Add(hurrem2);
        comboBox2.Items.Add(hurrem3);
        comboBox2.Items.Add(hurrem4);
        comboBox2.Items.Add(hurrem5);
        comboBox2.SelectedIndex = 0;

and

     private void button1_Click(object sender, EventArgs e)
    {
                  //..code
            Settings.Default["com5"] = Settings.Default["com4"];
            Settings.Default["com4"] = Settings.Default["com3"];
            Settings.Default["com3"] = Settings.Default["com2"];
            Settings.Default["com2"] = Settings.Default["com1"];
            Settings.Default["com1"] = path1.ToString();

            Settings.Default.Save();
emmett
  • 193
  • 2
  • 14

1 Answers1

1

You can use the LimitedStack from here: Limit size of Queue<T> in .NET?. You could then add methods for serializing/deserializing the data using Settings.Default.

public void Save()
{
  int i = 0;
  foreach (var item in _stack)
  {
    Settings.Default["com" + i++] = item;
  }

  Settings.Default.Save();
}

public void Load()
{
  for (int i = 0; i < Limit; i++)
  {
    _stack.Add((T)Settings.Default["com" + i++]);
  }
}

Storing the items (assuming you have the limited stack saved in a variable called myStack):

myStack.Push(path1.ToString());
myStack.Save();

Adding the items to the combobox:

for (int i = 0; i < myStack.Limit; i++)
{
  comboBox2.Items.Add(myStack.Pop());
}
Community
  • 1
  • 1
meilke
  • 3,280
  • 1
  • 15
  • 31