Oyeme
Oyeme

Reputation: 11225

C# listbox,params

As Andrew Hare suggested in his answer:

Create a field to store all the ListBox instances and then change the constructor to accept an arbitrary number of them.

I tried the following

class scaner
{
    readonly IEnumerable<ListBox> listBoxes;

    public IEnumerable<ListBox> ListBoxes
    {
        get { return this.listBoxes; }
    }

    public scaner(params ListBox[] listBoxes)
    {
        this.listBoxes = listBoxes;    
    }
}

This will allow you to do this:

scaner Comp = new scaner(listBox1, listBox2);

How can i access listbox1?

In class scaner i'm trying to call this.listBoxes.
(I need to call the listbox1 in scaner class.How can i do/call it?

Thanks for answers.

Upvotes: 0

Views: 223

Answers (3)

Jens Granlund
Jens Granlund

Reputation: 5070

You can use this property, something like this...

public class Scanner
{
    private readonly ListBox[] _listboxes;

    public Scanner(params ListBox[] listboxes)
    {
        _listboxes = listboxes;
    }

    public ListBox this[int index]
    {
        get
        {
            if(index < 0 || index > _listboxes.Length - 1) 
                throw new IndexOutOfRangeException();
            return _listboxes[index];
        }
    }
}

Usage:

ListBox listbox1 = new ListBox();
ListBox listbox2 = new ListBox();
var lst = new Scanner(listbox1, listbox2);
var lstbox1 = lst[0];

Upvotes: 0

Mark
Mark

Reputation: 10206

I might be off, but it looks like, from your other question, that you have five ListBox's that each have a different meaning, and you might do something special with each one. Instead of passing them all in on the constructor, and rely on them all to be in the right order, you might want to pass in an array of KeyValuePair<object,ListBox>. Then get at each with the key you assign.

I wouldn't rely on passing an params array in with a specific order. If you're going to need to do something very specific with the first one, and the second, etc.

I might be making too many assumptions from the other question though.

Upvotes: 2

John K&#228;ll&#233;n
John K&#228;ll&#233;n

Reputation: 7943

Why don't you store the array of listboxes as... an array?

public scanner
{
   private ListBox[] listboxes;

   public scanner(params ListBox[] listboxes)
   {
       this.listboxes = listboxes;
   }
}

Now you can access listbox1 in the call new scanner(listbox1, listbox2) as listboxes[0] in your scanner class.

Upvotes: 3

Related Questions