0

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 iterating through each statement.

Or can you point me to a practice that would make me achieve this? Or how to achieve this in less code?

1
  • Is it intentional that you are comparing different strings, e.g. (StringName == StringName2) vs. (StringName3 == StringName4)? This makes a big difference to the solution. Commented Jun 17, 2009 at 10:31

2 Answers 2

7

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

damn it! you beat me to it...+1
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);
@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!
1

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

myDict[StringName].Items.Add("send data")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.