0

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.

1

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.