1

I'm working on a product calculator program. Inside the app, the rep sale person can search for a client ID and the app shows him what services he can offer to client and his provision for sale. The form is generated acording to data i download from database. Right now I'm trying to store generated controls in lists. Every time a search is made, I dispose of controls and clear the lists. The thing i cant seem to get working is to store all the lists in single dictionary.

Something like this...

public class ListOfControls<T> : IListOfControls<T> where T : Control
{
    private readonly List<T> _controlsList;

    public ListOfControls()
    {
        _controlsList = new List<T>();
    }

    public void AddControll(T control)
    {
        _controlsList.Add(control);
    }

    public T this[int number]
    {
        get
        {
            return _controlsList[number];
        }
    }

    public void ClearControls()
    {
        _controlsList.Clear();
    }

    public T Last()
    {
        return _controlsList.Last();
    }
}

class DictionaryOfControlsLists
{
    //will be private - public only for test
    public readonly Dictionary<string, IListOfControls<Control>> _dictionaryOfLists;

    public DictionaryOfControlsLists()
    {
            _dictionaryOfLists = new Dictionary<string, IListOfControls<Control>>();
    }

    //Other code....

}

Now trying to implement...

DictionaryOfControlsLists _testDict = new DictionaryOfControlsLists();
_testDict._dictionaryOfLists.Add("test", new ListOfControls<Label>());

Sadly this wont work...Any ideas? THANKS

DavidWaldo
  • 661
  • 6
  • 24

1 Answers1

1

What you need is something like this:

class DictionaryOfControlsLists
{
    private readonly Dictionary<Type, IListOfControls<Control>> _dictionaryOfLists = new Dictionary<Type, IListOfControls<Control>>();

    public void Add<T>(T control) where T : Control
    {
        if (!_dictionaryOfLists.ContainsKey(typeof(T)))
        {
            _dictionaryOfLists[typeof(T)] = new ListOfControls<Control>();
        }
        _dictionaryOfLists[typeof(T)].AddControl(control);
    }

    public T Get<T>(int number) where T : Control
    {
        if (!_dictionaryOfLists.ContainsKey(typeof(T)))
        {
            _dictionaryOfLists[typeof(T)] = new ListOfControls<Control>();
        }
        return _dictionaryOfLists[typeof(T)][number] as T;
    }
}

Then you can do this:

DictionaryOfControlsLists _testDict = new DictionaryOfControlsLists();
_testDict.Add<Label>(new Label());
Label label = _testDict.Get<Label>(0);

If you need to extend this to have a string key then you need to implement a double dictionary within DictionaryOfControlsLists to handle it - something like a Dictionary<Type, Dictionary<string, IListOfControls<Control>>>.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172