Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i am studying c# recently and understand many object-oriented ideas.
acording to "event" in c# ,i think it is very useful. my question is:
if there is a main form and another subform in my project and the subform is
actived in mainform by constructing a subform object and calling showdialog method. at the same time there is a button in subform, when user click this button ,we can do something in button_click event handler funtion created by .net .
how can i inform the main form that the subform is now dealing with button_click event and set the focus on main form.
thanks.
Posted

Changing focus this way is a bad idea, but you can do the following for the events :

1) Expose the button on the subform by setting the modifier to public and attaching on to it in the main form.

2) Creating a new event and firing that in the sub form, and attaching on to it in the main form as before.
 
Share this answer
 
Because you are using the ShowDialog function to show your 2nd form, you won't be able to return focus to your main form without closing the new dialog. The first thing to do is to open your 2nd form using Show and not ShowDialog.
Then you can define an event in your second form. It can be as simple as this:
C#
public delegate void NoArgsEvent();
public event NoArgsEvent OnButtonClickEventNotify;

To cause the event to fire, just add a simple little block of code into your button click handler on form2.
if( OnButtonClickEventNotify != null )
{
    OnButtonClickEventNotify();
}


Then in your main form you just have to consume the event when you create an instance of your 2nd form:
C#
var dlg = new form2();
form2.OnButtonClickEventNotify += YourHandler;

void YourHandler()
{
    // Do something useful here.
    focus(); // To set the focus back to the main form.
}
 
Share this answer
 
Comments
Mehdi Gholam 1-Nov-11 12:27pm    
5'ed
fjdiewornncalwe 1-Nov-11 12:32pm    
Thank you, Mehdi.
wuxi_taihu 1-Nov-11 12:40pm    
i will have a try right now,thank you very much...
wuxi_taihu 1-Nov-11 13:18pm    
thanks again ,i have solved the problem according to your method.
There is no such concept as "subform", period. Please ask about something valid.

—SA
 
Share this answer
 
v2
Comments
wuxi_taihu 1-Nov-11 12:36pm    
sorry ,subform means another form which is shown by a function in main form
DaveyM69 1-Nov-11 16:21pm    
It's quite obvious that he means a 'Child' form i.e. one that is instanciated by another (main in this case) as the other posters realised.
As a regular in QA you should also realise that what you posted is a comment not a solution. I'll leave it for you to ammend.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900