user1108076
user1108076

Reputation: 81

C#, User Control, Events - User Control's Control Event Overriding?

In my C# program, I have a Custom Control with a label and a button. How can I setup my control so that when a user clicks the button it overrides the Custom Control's Click event?

Upvotes: 1

Views: 4989

Answers (3)

Pranay Rana
Pranay Rana

Reputation: 176896

Here is full article which explain you how you can achieve it : Exposing Custom event from custom control

Following is step for the drodown used in user control and exposing event you need to do same for you button , you will get more idea after reading above link

Step 1 : Register event in user control cs file

public event EventHandler DrpChange;

Step 2 : Virtual function to handle raised event in usercontrol cs file

public virtual void OnDropDownChange()
    {
        if (DrpChange != null)
        {
            this.DrpChange(this, EventArgs.Empty);
        }
    }

Step 3 : Register on Change Event of dropdown in ASCX.CS file

protected void ddlDropDown_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.OnDropDownChange();
    }

Step 4 : Use User control on page and utilize expose custom event .Aspx page

<uc1:commondropdowncontrol autopostback="true" drpchange="usrDrp_DrpChange" id="usrDrp" labletext="Country" runat="server">
    </uc1:commondropdowncontrol></div>
</form>

Upvotes: 0

LarsTech
LarsTech

Reputation: 81610

You can write it like this:

public new event EventHandler Click {
  add { button1.Click += value; }
  remove { button1.Click -= value; }
}

Upvotes: 1

Hans Passant
Hans Passant

Reputation: 941455

Simply call the control's OnClick() method:

    private void button1_Click(object sender, EventArgs e) {
        this.OnClick(e);
    }

Which fires the control's Click event.

Upvotes: 2

Related Questions