views:

61

answers:

1

I'm getting into event handling now, and it seems quite confusing to me. See, I come from a web-dev background, so this event stuff is quite new to me.

I'm developing in C# / VS08 and created my Application in the WinForm-Designer.

Now, I created this program overview;

ProgramContext
 MainForm : Form
 LoginForm : Form

So, what I want to do is when the user clicks "Logout" (What is a menu item in the MainMenu of MainForm), that the application logs out the user.

But how can I access the "Click" event of the logout item from the ProgramContext's view, as there is all the logic of logging in etc.

I tried the following

MenuItem[] findLogout = MainMenuStrip.Items.Find("logoutMenuItem", true); // Throws NullPointerException
findLogout[0].Click += new EventHandler(LogoutClick);

private void LogoutClick(object sender, EventArgs e)
{
 // Logout user
}

But keep getting a NullPointerException at the first line.

+2  A: 

Easiest thing to do is to expose an event on MainForm:

public EventHandler LogOut;

Then hook into this from your ProgramContext:

MainForm form = new MainForm();
form.LogOut += new EventHandler(MainForm_LogOut);

void MainForm_LogOut(object sender, EventArgs e)
{
    // Logout
}

Then fire the LogOut button is pressed on the MainMenu using the following code in the Menu Item's click event:

private void LogoutClick(object sender, EventArgs e)
{
    if (LogOut != null)
    {
        LogOut(sender, e);
    }
}
GenericTypeTea
So, just to clarify - is that the pratice-to-go or just a small workaround? If second, how do you do it "the best way"? Is my approach of program design wrong?!
ApoY2k
@ApoY2k - This is the practice I use personally. Say, for example, you add another log out button to your MainForm, or you add a timeout which causes a log out. Wouldn't you want that to be communicated back to the Program Context as well? Using your current method you'd need to capture an event per object that causes a log out. With my example, you just call `LogOut(sender, e);` at any pont where you want to do a logout.
GenericTypeTea