views:

27

answers:

1

I am trying to change a value in the event arguments. Not sure if this is possible, but this is my current event in the parent class:

public void MasterClass()
{
   void btnSubmit_Click(object sender, EventArgs e)
   {
     ...
     OnInputBound(this, new InputEventArgs(postName, value));

     //I would like to try something like this but does not work:
     //value = OnInputBound(this, new InputEventArgs(postName, value));

     //Continue with new value...
   }
}

In other parts of the application, they register the event normally like this:

protected override void CreateChildControls()
{
    MyForm.OnInputBound += new EventHandler<InputEventArgs>(MyForm_OnInputBound);
}

void MyForm_OnInputBound(object sender, SingleForm.InputEventArgs e)
{
    e.Value = "new value";
}

Notice how I am trying to change the argument for the MasterClass. This is obviously not working, but how would I bubble this value up?

+1  A: 

You will need to hold on to a reference to the InputEventArgs instance so that you can read the Value from it after the event has been raised:

void btnSubmit_Click(object sender, EventArgs e)
{
    ...
    InputEventArgs eventArgs = new InputEventArgs(postName, value);
    OnInputBound(this, eventArgs);

    value = eventArgs.Value;

    //Continue with new value...
}

One thing to be aware of here is that there are scenarios that may lead to unexpected results:

  • The listener can choose to spawn a thread and process the call asynchronously
  • There may be a number of listeners for the same event, each of which may assign a different value. Your code will of course only see the last one assigned, but you will have no control over the order in which the listeners are invoked.

Take the following case for instance (first point above):

void MyForm_OnInputBound(object sender, SingleForm.InputEventArgs e)
{
    ThreadPool.QueueUserWorkItem(state => 
    {
        // perform some potentially lengthy database lookup or such
        // and then assign a new value
        e.Value = "new value";
    });

}

In this case there is no guarantee that the value is assigned before your code in btnSubmit_Click picks up the "new" value from the InputEventArgs instance.

Fredrik Mörk