0
votes

So I have a form on a WinForms app. On that form is a FlowLayoutPanel. On the FlowLayout panel is a bunch of user controls each representing rows from a table from a database. On each control is a button.

How do I have the form subscribe to a button click on one of the controls passing back that rows database info?

This is the control code:

public partial class ctrlLeague : UserControl
{
    public League activeLeague = new League();
    public event EventHandler<MyEventArgs> ViewLeagueClicked;
    public ctrlLeague(League lg)
    {
        InitializeComponent();
        lblLeagueName.Text = lg.leagueName;
        activeLeague = lg;
    }

    private void btnViewLeague_Click(object sender, EventArgs e)
    {
        ViewLeagueClicked(this, new MyEventArgs(activeLeague));
    }

    public class MyEventArgs : EventArgs
    {
        public MyEventArgs(League activeLeague)
        {
            ActiveLeague = activeLeague;
        }
        public League ActiveLeague { get; }
    }
}

if I put the following into the form constructor it tells me "

1
So the button is on the ctrLeague user control? Then just subscribe to the evant as usual (btn.Click += btnViewLeague_Click).Klaus Gütter
But my form can not see this event like it does my other events. I assume this is because it is within a control, within a FlowLayoutPanel and there are multiple instances of this control.Joe Brown
I untersood that you want to subscribe the event in the UserControl, not the Form.Klaus Gütter
My apologies if that wasn't clear.Joe Brown

1 Answers

1
votes

You can define your favorite event with delegate and call it wherever you want, here it is called inside btnView_Click.

This means that whenever btnView_Click called, your event is actually called.

public partial class ctrlLeague : UserControl
{
    public League activeLeague = new League();
    public event EventViewLeagueClicked ViewLeagueClicked;
    public delegate void EventViewLeagueClicked(object Sender);


    public ctrlLeague(League lg)
    {
       InitializeComponent();
       lblLeagueName.Text = lg.leagueName;
       activeLeague = lg;
    }

    private void btnViewLeague_Click(object sender, EventArgs e)
    {
       if (ViewLeagueClicked != null)
         ViewLeagueClicked(activeLeague);
    }
}

now use

public Form1()
{
    InitializeComponent();
    League league = new League();
    league.leagueName = "Seri A";
    
    
    //
    //These lines are best added in Form1.Designer.cs
    //
    ctrlLeague control = new ctrlLeague(league);
    control.Location = new System.Drawing.Point(350, 50);
    control.Name = "ctrlLeague";
    control.Size = new System.Drawing.Size(150, 100);
    control.ViewLeagueClicked += Control_ViewLeagueClicked;
    this.Controls.Add(control);
}
private void Control_ViewLeagueClicked(object Sender)
{
   League l = Sender as League;
   MessageBox.Show(l.leagueName);
}