North
North

Reputation: 75

C# Programming practice

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?

Upvotes: 0

Views: 795

Answers (2)

van
van

Reputation: 76992

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

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

Upvotes: 1

Kirschstein
Kirschstein

Reputation: 14868

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);
}

Upvotes: 7

Related Questions