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 Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Adding an eventhandler to a list box at runtime

Status
Not open for further replies.

adrianjohnson

Programmer
May 16, 2002
145
GB
Hello,

I've got a function which reads a text box, and creates a tabpage with a listbox on the fly. This means there may be more than one listbox at any one time.

Within my code, I create an event handler for the listbox. It fires off ok, but I'd like to get the selected text from the listbox, but I can't seem to retreive it. I know I can use the listbox.selecteditem etc code, but it doesn't work.

Here's my code:

Code:
TabPage newPage = new TabPage(strLine);

// Create a list view, and add it to the new tab.
newList = new ListBox();
newPage.Controls.Add(newList);
newList.Dock = DockStyle.Fill;

newList.Click += new EventHandler(newList_Click);

The event handler code (I'm just trying to see what it returns) is:

Code:
private void newList_Click(object sender, EventArgs e)
{
 MessageBox.Show(sender.GetType().ToString());
 //MessageBox.Show(sender.ToString());
 Console.WriteLine(sender.ToString());
}

Any ideas?

Thanks,

Adrian
 
I suggest hooking up on the SelectedIndexChanged event instead. Click will trigger when you, well, click, anywhere on the Listbox even when it's empty.
Code:
newlist.SelectedIndexChanged += new EventHandler(newList_SelectedIndexChanged);

...

void newList_SelectedIndexChanged(object sender, EventArgs e)
{
  ListBox lbox = (ListBox)sender;
  MessageBox.Show(lbox.SelectedIndex.ToString());
}
I'm assuming that for all your listboxes, they will all have a common event handler. This is fine since the sender param will always point to the correct ListBox control where the event actually occurred. Then, retrieve the selected item with the SelectedIndex or SelectedItem properties. Read on these properties on how to use them.

Hope this helps. [wink]
 
I recommend a listview as an alternative to the listbox. It is a much cleaner control with more functionality.

The selected index changed sometimes throws back null for selectedindex still so you have to do a check at the start anyways

listbox1_SelectedIndexChanged(object Sender, EventArgs e)
{
if (listbox1.SelectedItem != null)
{
//do your work...
}
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top