Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Pass ListBox Items to an array

Status
Not open for further replies.

Gill1978

Programmer
Joined
Jun 12, 2001
Messages
277
Location
GB
Hi,

I'm very new to C# ... so I don't really know how to interpret potential solutions ... like the one below given below:

Not sure what the <string> bit means ... do I pass the name of the ListBox (which contains the collection I need to pass) ... or is this a new variable?

Code:
protected void SomeEvent(...)
{
   //get selected values
   List<string> selected = new List<string>();
   foreach(ListItem item in myControl.Items)
   {
        if(item.selected)
        {
            selected.Add(item.Value);
        }
   }
   //call function
   MyClass c = new MyClass(...);
   c.MyFunction(selected.ToArray());
}

Thanks for any help ...

J
 
Hiya Sunil,

That did help with that line ... changed it to this:
Code:
System.Collections.Generic.List<String> selected = new System.Collections.Generic.List<String>();

Got an issue with the next line (mycontrol)
foreach(ListItem item in myControl.Items)

Obviously I don't understand the mycontrol bit ...

Can you give me a hint on this to ... :)

Thanks

J

 
Basically the foreach loop is iterating through all the ListItems in the myControl, which I assume is a listbox control and finding all the Items (ListItems) that have been selected by the user and adding the value of the selected items to the "selected" variable. So at the end of the loop you have a collection of item values that have been selected by the user in "selected" variable.

Hope this helps.


Sunil
 
Sorry got the wrong line ... that was the ListBox control!!!

I meant the MyClass bit ... not sure what that bit is ...

 
Ok.. with last few lines MyClass is being instantiated and the object is held in the variable c and the method myFunction is called which looks like it takes an array of strings. the function definition should be something like.

Code:
public  void myFunction(string[] variableName)
{
  ....
  Some code here
  ...
}

Now selected.ToArray() methods returns an array of string which is being sent to myFunction.




Sunil
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top