Daniel
Daniel

Reputation: 526

Raise event in another class in order to execute a function in FormMain, and more parameters are passed

I have problems with the C# syntax when it comes to events.

I have the following code in FormMain: 1.) private TextfileParser TfP = new TextfileParser(); 2.) (in FormMain_Load) TfP.MR += new TextfileParser.MessageBox_required(); 3.) the procedure to be executed.

private void MessageBox_required(object sender, EventArgs e, string s)
        {
            MessageBox.Show(s,
                            "Database – Load Data",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
        }

TextfileParser.cs contains the following code:

public delegate void MessageBox_required(object sender, EventArgs e, string Text);
public event MessageBox_required MR;

The error reads:

Compiler Error CS1729: "TextfileParser.MessageBox_required" does not contain a constructor that takes 0 arguments.

where the error is

If I put in arguments, that's also wrong.

I can't cope with the examples on various websites and forums, especially because people create extra classes and procedures. I can't imagine that this has to be done in such a “complicated” way. Also, I have to pass another parameter (string Text).

Upvotes: 0

Views: 44

Answers (1)

Batesias
Batesias

Reputation: 2146

Right now, your handler method has the same name as the delegate. For clarity, let's rename your handler method like the following:

private void OnMessageBoxRequired(object sender, EventArgs e, string s)
{
    MessageBox.Show(s,
        "Database – Load Data",
        MessageBoxButtons.OK,
        MessageBoxIcon.Error);
}

The correct syntax to subscribe to your event would then be the following:

TfP.MR += OnMessageBoxRequired;

To raise the event, your TextfileParser class needs to do the following:

MR?.Invoke(this, EventArgs.Empty, "some string");

Upvotes: 1

Related Questions