As a follow up to: access values within custom eventargs class
How do I access public variables within custom Eventargs class, using button click or any other method?
Example Custom Event Args class:
public class TraderEventArgs: EventArgs
{
private int _shares;
private string _symbol;
public TraderEventArgs(int shs, string sym)
{
this._shares = shs;
this._symbol = sym;
}
public decimal Price
{
get {return _prices;}
}
public int Shares
{
get { return _shares; }
}
}
Code behind button_click event:
public partial class _Default : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
// run trader app
myApp.Main();
// try to access TraderEventArgs class
TraderEventArgs: EventArgs ev = TraderEventArgs: EventArgs(); // Invalid
TraderEventArgs ev = new TraderEventArgs(); // this needs argument variables that are unassigned... ?
TraderEventArgs ev = (TraderEventArgs)e; // Unable to cast object of type 'System.EventArgs' to type TraderEventArgs'.
string sym = ev.Symbol.ToString();
string sharws = ev.Shares.ToString();
// do something with data
}
thanks for help.
Solution: Pass custom event args through a custom delegate and event that returns the data (Datatable, Array, etc)...using whatever button click or other event necessary.
So as a function of the delegate the correct data is returned.. I can not post the complete code here, but it is a modification of this very excellent example on event delegate usage...
Core C# and .NET 3.7. Delegates and Events http://flylib.com/books/en/4.253.1.38/1/
When the button click event is raised, it's creating the
EventArgs
that gets passed into "e". That object was not created by you, but rather by the framework itself, and is of typeEventArgs
. This prevents you from being able to cast it to a different type.If you want to have an event that raises
TraderEventArgs
, you need to create an event, preferably of typeEventHandler<TraderEventArgs>
, and raise this event somewhere that is in your control. This allows you to generate the class of the correct type, then handle it (in a separate event handler) directly.You can't do that. The
EventArgs
of theClick
event is always of typeEventArgs
; you can't expect it to be of typeTraderEventArgs
, because the event args is created by the button, and the button doesn't know anything aboutTraderEventArgs
. The only way it could work is if you create your ownButton
control that raises the event with aTraderEventArgs
instead of anEventArgs