Zhenia
Zhenia

Reputation: 4179

Delegate and event

I have 2 forms.

Form1:

public partial class Panel1
    {
        public void ShowExport(object sender, EventArgs e)
        {
           .......
        }
    }

Form2:

public partial class Panel2
{
        public delegate void ShowExportReport(object sender, EventArgs e);
        public event ShowExportReport ShowExportClicked;

private void buttonExport_Click(object sender, RoutedEventArgs e)
        {         
           if (ShowExportClicked != null)
            {
                ShowExportClicked(sender, new EventArgs());
            }                     

        }
}

When I click button -

button.Click = buttonExport_Click

How can I call Panel1.ShowExport() from Panel2.buttonExport_Click?

Upvotes: 1

Views: 204

Answers (5)

Igoy
Igoy

Reputation: 2962

You need to assign the handler for the event ShowExportClicked in Panel 1 class to the Panel 2 class object.

     public partial class Panel1
        {
            Panel2 pnl2;
            public Panel1()
            {
               pnl2 = new Panel2();
               pnl2.ShowExportClicked += new ShowExportReport(ShowExport);    
            }

            public void ShowExport(object sender, EventArgs e)
            {
               .......
            }
        }

Upvotes: 2

CodeCaster
CodeCaster

Reputation: 151594

How can I call Panel1.ShowExport() from Panel2.buttonExport_Click?

By passing (only the necessary) information from form1 when instantiating form2.

Form1.cs:

void ShowForm2_Click()
{
    var form2 = new Form2();
    form2.ShowExportClicked += ShowExport;
    form2.Show();
}

Now from Form2 you can simply call ShowExport on button click.

Upvotes: 0

Zaki
Zaki

Reputation: 5600

Create your event on Form1. and listen to the event in Form2.

Form1:

public event EventHandler ShowExportChanged;

private void ShowExportChanged()
{
    var handler = ShowExportChanged;
    if(handler == null)
        return;

    handler(this, EventArgs.Empty);
}

public void ShowExport(object sender, EventArgs e)
{
  ShowExportChanged();
}

Form2:

pnl1.ShowExportChanged+= new OnShowExportChanged(ShowExportChanged);

Upvotes: 0

Reza ArabQaeni
Reza ArabQaeni

Reputation: 4907

pnl2.ShowExportClicked += ShowExport;

Upvotes: 0

Stefano Altieri
Stefano Altieri

Reputation: 4628

In the Panel1 you have to subscribe the event:

pnl2.ShowExportClicked += new ShowExportReport(ShowExport);

Upvotes: 2

Related Questions