Search code examples
c#visual-studiocombobox

can I add a list of variable names to a combobox in C#


I have a long list of arrays, and I want to make a dropdown box to see all the names of the arrays. I don't want to pre-enter the names to the dropdown box, and I want to avoid the multiple lines of dynamically entering the names.

eg,

int[] Brett = { 24, 64, 83 };

int[] Tony = { 32, 78, 27 };

The combobox dropdowns would show Brett and Tony

I am new to programming so if there is a basic solution I would understand I would prefer it to an advanced way of doing it. Thanks for any help at all though!


Solution

  • I'm pretty sure that you have XY-problem, but nameof() is the answer to your local question:

    ComboBox mybox = new ComboBox();
    mybox.Items.Add(nameof(Brett));
    mybox.Items.Add(nameof(Tony));
    

    Let's try to sort out your case. I think that use long list of variables is not good idea so the better way is to use list of classes or Dictionary like this:

    var parameters = new Dictionary<string, int[]>();
    parameters.Add("Brett", new [] { 24, 64, 83 });
    parameters.Add("Tony", new [] { 32, 78, 27 });
    

    It'll help you to add items easier:

    foreach(var kvp in parameters)
        mybox.Items.Add(kvp.Key);
    

    The alternative with classes is in the code below:

    public class PersonParams
    {
        public string Name { get; }
        public int[] Params { get; }
        public PersonParams(string name, params int [] p)
        {
            Name = name;
            Params = p;
        }
    }
    ...
    var persons = new List<PersonParams>();
    persons.Add(new PersonParams("Brett", 24, 64, 83));
    persons.Add(new PersonParams("Tony", 32, 78, 27));
    ...
    foreach(var p in persons)
        mybox.Items.Add(p.Name);