Question

related to this topic: https://stackoverflow.com/questions/15170054/context-hint-using-combobox

Is there a way I can use the strings in my separate class:

namespace KeyWord
{
    public class KeyWord
    {
        //Definitions
    public String[] keywords = { "abstract", "as", "etc." };
    }
}

to mylistbox items in my mainform?

lb = new ListBox();
        Controls.Add(lb);

ty in advance

Was it helpful?

Solution

Sure. Try something like this.

KeyWord kw = new KeyWord();
foreach (string str in kw.keywords)
{
    lb.Items.Add(str);
}

Or you can use databinding.

Also, if all you're doing is getting an array of strings from that class, you might want to use a static property so you don't have to instantiate an instance of that object. I would recommend using properties either way for exposing public data, instead of a public field.

Here's an example of using a static property, instead:

public class KeyWord
{
    // Private field, only accessible within this class
    private static string[] _keywords = { "abstract", "as", "etc." };

    // Public Static Property, accessible wherever
    public static string[] Keywords
    {
        get { return _keywords; }
        set { _keywords = value; }
    }
}

Then:

foreach (string str in KeyWord.Keywords)
{
    lb.Items.Add(str);
}

Notice, I didn't instantiate the class in this example (no new KeyWords())

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top