tags:

views:

292

answers:

2

i want to update a control based on a value e.g

       if (StringName == StringName2) 
            ListBox1.Items.Add("send data");
        else if (StringName3 == StringName4)
            DifferentListBox.Items.Add("send data");
        else if (StringName5 == StringName3)
            AnotherListBox.Items.Add("send data");

// or done using a switch statement

// and so on another 20 times for example

is it possible to put these methods \\ (OneOfTheListBoxes.Items.Add("send data") \\ to be put in a dictionary so i only need to enter the key to action the method instead of itterating through each statement.

or can u point me to a practice that would make me acheive this? or achieve this in less code.

sorry for noob question

+6  A: 

Yes, you could put all the of the listboxes into a dictionary like so;

Dictionary<string, ListBox> _Dictionary;

public Something() //constructor
{
   _Dictionary= new Dictionary<string, ListBox>();
   _Dictionary.add("stringname1", ListBox1);
   _Dictionary.add("stringname2", ListBox2);
   _Dictionary.add("stringname3", ListBox3);
}


....


public void AddToListBox(string listBoxName, string valueToAdd)
{
  var listBox = _Dictionary[listBoxName];
  listBox.Items.Add(valueToAdd);
}
Kirschstein
damn it! you beat me to it...+1
Pondidum
Kirschstein has a great solution. If annakata's (below) point is valid: you're testing against different strings, you can still use this solution as long as there is a 1:* string:ListBox relationship, just enter the ListBox more than once in the Dictionary.e.g.,_Dictionary.Add("string1", ListBox1);_Dictionary.Add("string2", ListBox1);
Mark
If i could buy you an e-beer i would thank you very much :D
North
@North, not a problem!@Mark, I noticed the comparing of different strings a little while after I posted and started looking for a solution to it if this was the case, quite tricky!
Kirschstein
A: 

Sure. Use dictionary with the key holding a StringName, and value holding a Listbox. Then use:

myDict[StringName].Items.Add("send data")
van
x2 for you too :D
North