Иван Желев Иван Желев - 1 month ago 18
C# Question

Multiple OnClick events in c#

I want to ask if i have multiple labels with same function Onclick but with different parameters. How i can handle them without make 30 methods.
I want to make A-Z Filter in windows forms application with C#. I have label for each character (A,B,C,D....,Z). Also i have TreeView with data from DB.

private void labelLetter1_Click(object sender, EventArgs e)
{
//this.labelLetter1.Text
// get value of the label and refresh treeview
}


I want to make this on every characters but without repeat same code.

Answer

subscribe an example event to other ones. try like this:

private void labelLetter1_Click(object sender, EventArgs e)
 {
     Label lbl = (Label) sender;
     var text = lbl.Text;
    //this.labelLetter1.Text
   // get value of the label and refresh treeview
 }

now set this event to other labels from Properties window.