C# forms callback
I have two forms:
class Form开发者_StackOverflowA : Form
{
Initialise()
{/*Some code */}
btnAdd_Click()
{
FormB formB = new FormB() //control is given to FormB
}
}
class FormB : Form
{
btnOK_Click()
{
//When this is pressed FormB closes and passes a string back to FormA.
//I also what a function in FormA to be called.
}
}
So there is the event this.btnOK.Click. From what I can see I have two options:
1) Pass a function to FormB from FormA (say in the ctor) and call this function inside btnOK_Click passing it the string argument.
2) Register a method with the btnOK.Click event. However I don't know where to put this registration. I want to put it in the ctor of FormA so that it is registered only once (e.g. if I put it in btnAdd_Click when the user presses btnAdd in FormA several times the method will get registered several times.
There are so many ways to go. Can you show me what a good method will be?
EDIT 1: I also don't know how to register a method in FormA with the this.btnOK.Click event that belongs to FormB. Ideally I can do this in the ctor of FormA.
Make Action Delegate (Event) in FormB that FormA can suscribe. Then btnOK_Click trigger(call) that event.
class FormA:Form {
...
btnAdd_Click(){
FormB formB = new FormB();
formB.CallBack += this.OnCallBack;
}
private void OnCallBack(object sender, EventArgs args){
// put your process here
}
}
class FormB:Form {
...
btnOK_Click(){
EventHandler<EventArgs> handler = this.CallBack;
// if not null, call handler
if (handler != null)
{
// you can make custom EventArgs, pass parameter with it
handler(this, new EventArgs());
}
}
Event EventHandler<EventArgs> CallBack;
}
To pass parameter you can make a custom EventArgs.
class CustomEventArgs : EventArgs {
public string Param1 {get; set;}
public int Param2 {get; set;}
public bool Param3 {get; set;}
...
}
class FormA:Form {
...
private void OnCallBack(object sender, CustomEventArgs args){
// put your process here
...
}
}
class FormB:Form {
...
btnOK_Click(){
EventHandler<CustomEventArgs> handler = this.CallBack;
if (handler != null)
{
// set parameter
CustomEventArgs eventArgs = new CustomEventArgs();
eventArgs.Param1 = "param1";
eventArgs.Param2 = 1000;
eventArgs.Param3 = true;
// call handler and pass value
handler(this, eventArgs);
}
}
Event EventHandler<CustomEventArgs> CallBack;
}
Passing the FormA instance to the FormB and calling FormA public method is the object oriented way of implementing this.
For example. FormB constructor can be like below
FormA myFormA;
public FormB(FormA formA)
{
myFormA = formA;
}
private void CallFormAMethods()
{
myFormA.CallPublicMethod();
}
精彩评论