0

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

Community
  • 1
  • 1

1 Answers1

0

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())

Adam Plocher
  • 13,994
  • 6
  • 46
  • 79
  • A new expression requires (), [], or {} after type , pointing the KeyWord; –  Mar 02 '13 at 04:04
  • I fixed it about 10 seconds after I posted it :P ... `new KeyWord();` (forgot the parentheses at first) – Adam Plocher Mar 02 '13 at 04:06
  • nice you got it right sir really thanks for that, but what if i need to apply 2individual group of strings in just a listbox? is that possible also sir? like: public String[] keywords and public String[] events from class –  Mar 02 '13 at 04:09
  • I'm not sure I understand what you mean. You just want to add two arrays to the list? You can continue to append values to the listBox by calling `lb.Items.Add("something else");` – Adam Plocher Mar 02 '13 at 04:10
  • answered by myself: KeyWord keywordsL = new KeyWord(); KeyWord eventsL = new KeyWord(); foreach (string str in keywordsL.keywords) { lb.Items.Add(str); } foreach (string str in eventsL.events) { lb.Items.Add(str); } gee really thanks for the help :D –  Mar 02 '13 at 04:12