问题
I have a usercontrol
which is having one button
Usercontrolclass.cs
Button click event
private void btn_OK_Click(object sender, EventArgs e)
{
value= Convert.ToDouble(txt_ActualValue.Text);
if(getvalue!=null)
getvalue(null, new EventArga());
}
private variable
private int value;
property:
public double finalvalue
{
get
{
return value;
}
}
MainForm.cs
I'm using that Usercontrol into this mainform
I need to get the value from this class
in constructor:
Usercontrolclass.getvalue+=Usercontrolclass_getvalue;
in method:
private void UserControlclass_getvalue()
{
here I need to get the "value";
int myval = Usercontrolclass.finalvalue; // I can get like this
}
my question is without using properties simply pass a parameter into the event arguments and get the value in to the mainfrom?
if(getvalue!=null)
getvalue(null, new EventArga(value));
Because I don't allowed to do like this classname.properties
as well as don't allowed to pass a parameter using method like this
in Usercontrol class
Mainform obj = new Mainform ();
obj.getvalue(value);
Is there any other way to do this? I mean pass a variable to another class by using events?
回答1:
You can make your own events
, you can fire them from the usercontrol
(here is where the event takes place) and put a listener on your main form.
User control:
//You custom event, has to be inside namespace but outside class
public delegate void MyCustomEvent(int value);
public partial class aUserControl : UserControl
{
//Here you initialize it
public event MyCustomEvent CustomEvent;
public aUserControl()
{
InitializeComponent();
}
private void theButton_Click( object sender, EventArgs e )
{
CustomEvent?.Invoke(5);//using magic number for test
//You can call this anywhere in the user control to fire the event
}
}
Now in the main form I added the usercontrol and an event listener
Main form:
public Form1()
{
InitializeComponent();
//Here you add the event listener to your user control
aUserControl1.CustomEvent += AUserControl1_CustomEvent;
}
private void AUserControl1_CustomEvent( int value )
{
MessageBox.Show(value.ToString());
//This is the Main form and I now have the value here
//whenever the button is clicked (or event is fired from somewhere else)
}
来源:https://stackoverflow.com/questions/45182850/how-to-pass-a-parameter-to-another-class-using-events