user3755946 user3755946 - 4 months ago 6
C# Question

I want my container to be the sender of an event triggered by a control that it contains

The code bellow works but I need the sender to be the SpecialTextBox and not the TextBox within the SpecialTextBox. The reason is I need to get the "IdCode" from the SpecialTextBox When it's TextBox.Leave event is triggered.

As this works the sender seems to be the TextBox within the SpecialTextBox.

Hope this makes sense...

My panel that will contain text boxes...

class BigPanel: Panel
{
SpecialTextBox stb = new SpecialTextBox();

public BigPanel()
{
BorderStyle = BorderStyle.FixedSingle;
stb.SpecialTBLeave += Stb_SpecialTBLeave;
Controls.Add(stb);

}

private void Stb_SpecialTBLeave(object sender, EventArgs e)
{
SpecialTextBox s = (sender as SpecialTextBox);


}
}


My "Special" Text Box I have removed most of the functionality to keep the example simple.

class SpecialTextBox : Panel
{
TextBox tb = new TextBox();
public string IdCode {get; set;}
public SpecialTextBox()
{

Controls.Add(tb);
BorderStyle = BorderStyle.FixedSingle;
Left = 30;
}



public event EventHandler SpecialTBLeave
{
add { this.tb.Click += value; }
remove { this.tb.Click -= value; }
}
}


The code on my main form...

BigPanel bp = new BigPanel();

Controls.Add(bp);

Answer

You need to handle the events of the inner TextBox inside your SpecialTextBox and provide new events to be consumed from outside:

class SpecialTextBox : Panel
{
    TextBox tb = new TextBox();
    public string IdCode {get; set;}

    // simple event, don't register to the inner TextBox!
    public event EventHandler SpecialTBLeave;

    public SpecialTextBox()
    {
        Controls.Add(tb);
        BorderStyle = BorderStyle.FixedSingle;
        Left = 30;

        // register to inner TextBox' event to raise outer event
        tb.Leave += (sender, e) => SpecialTBLeave?.Invoke(this, e);
    }
}

Since you inherit from Panel, you may consider to use Panel's already existing Leave event instead of creating a new one:

public SpecialTextBox()
{
    tb.Leave += (sender, e) => base.OnLeave(e);       
}