Search code examples
c#event-handlingparameter-passingoptional-parameters

Pass number into event


I would like to ask you for help. I dynamically creating a lot of textboxes and I am using LostFocus event (C#).

Is it possible to create event with passing of number ID of textbox?

Something like

(object sender,EventArgs,int ID)

and

tbx.LostFocus+= EventHandler(MySubFunction(3)?? --3 is my ID of textbox

Thank you for help, I am lost in this I do not know how to add any number to EventHandler call


Solution

  • If you are using winforms you can use the Tag property to distinguish between different controls:

    var textbox = new TextBox();
    textbox.Tag = 42;
    textbox.LostFocus += TextboxLostFocus;
    
    ...
    void TextboxLostFocus(object sender, EventArgs e){
       if(sender is TextBox txtBox && txtBox.Tag is int textboxNum){
          // use textboxNum
       }
    }
    

    Or you can use lambdas to register your event with a built in number:

    var textbox = new TextBox();
    textbox.LostFocus += (o, e) => TextboxLostFocus(42);
    
    ...
    void TextboxLostFocus(int textboxNum){
          // use textboxNum
    }