webworm
webworm

Reputation: 11019

Single event handler for multiple links/buttons on ASP.NET

I have a dropdown list that contains a collection of names. My entire names list is very large (over 2,000) so I would like to pair down the names in the drop down list to those starting with the same letter.

To do this I would like to have 26 links all on the same line, one for each letter in the alphabet ..

A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z

The idea being that the user clicks on the letter they are interested in and the stored procedure that obtains the list of names is re-executed to only grab those names starting with the letter that was clicked and then the resulting dataset is rebound to the dropdown list.

What is vexing me is how to handle creating all the "Click Events" necessary to deal with the user "clicking" on a link. I could create 26 different event handlers, one for each link, but I have to believe there is a simpler way I am not seeing.

Form demonstration here is the click event for one link, the letter "A" ...

      Protected Sub lnkLetterA_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lnkLeterA.Click
        Call LoadNamesIntoDropDown("A")
      End Sub

Is there a way to create one event handler that could handle all 26 links? Thank you.

P.S. C# or VB.NET examples are fine. I just happen to be using VB.NET in this case.

Upvotes: 0

Views: 4025

Answers (3)

Vadim
Vadim

Reputation: 17957

You can reuse the same click handler a simple example

protected void HandleLinkClick(object sender, EventArgs e)
{
    HyperLink link = (HyperLink)sender;
    LoadNamesIntoDropDown(link.Text);
}

However, there are loads of autocomplete style solutions you can use. A free one from MS http://www.asp.net/ajax/ajaxcontroltoolkit/samples/autocomplete/autocomplete.aspx

Upvotes: 2

anothershrubery
anothershrubery

Reputation: 20993

As per your example use:

Protected Sub lnkLetter_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lnkLeterA.Click, lnkLeterB.Click, lnkLeterC.Click //etc
        Call LoadNamesIntoDropDown(CType(sender, LinkLabel).Text)
End Sub

Upvotes: 1

Fredrik Mörk
Fredrik Mörk

Reputation: 158299

Of course you can have one handler to rule them all. Just connect the Click event of all the links to the same method.

Do you create the links dynamically in code-behind, or have you created them in the designer? If it is done in the designer:

  • Select a link
  • In the property grid, switch to the event view
  • In the click event, select your event handler from the dropdown list
  • Repeat for all links

In the event handler, use the sender argument to examine which of the links that was clicked, and act accordingly.

Upvotes: 1

Related Questions