Click here to Skip to main content
15,888,097 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
How to call SelectedItem of a listbox that is created dynamically using foreach, from form1 to form2, and it is contained in a tabcontroll in form2.

Example:
form2.tabcontrol.tabpages.clear()
Foreach (string word in textbox)
{
tabpage tp = new tabpage;
form2.tabcontrol.tabpage.add(tp)
Listbox lb = new Listbox;
tp.controls.add(lb);
}
Posted
Updated 16-Aug-10 21:24pm
v2

1 solution

Subscribe to the lb.SelectedIndexChanged event.

tabpage tp = new tabpage;
form2.tabcontrol.tabpage.add(tp)
Listbox lb = new Listbox;
lb.SelectedIndexChanged += new EventHandler(lb_SelectedIndexChanged);
tp.controls.add(lb);


Once an item is clicked, you can get the selected indexes (or index):
<br />
void lb_SelectedIndexChanged(object sender, EventArgs e)<br />
{<br />
<pre><br />
    ListBox lb = sender as ListBox;<br />
    int selectedIndex = lb.SelectedIndex;<br />
    //For multiple selections<br />
    System.Windows.Forms.ListBox.SelectedIndexCollection   <br />
    selectedCollection = lb.SelectedIndices;<br />
</pre><br />
}<br />
<br />
 
Share this answer
 
Comments
Daniel262 18-Aug-10 2:16am    
Well,
I actually don't know how i can use this, because i have a button that uses the selected item.
So the problem is that i cannot access the listbox because it is in the foreach.
Fayu 18-Aug-10 8:57am    
In lb_SelectedIndexChanged, you can assign the selected indices in a class variable. When you click the button, you can refer to the variable which will contain the values you are looking for.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900