define Custom Event for WebControl in asp.net

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-01 01:31:22

问题


I need to define 3 events in a Custom Control as OnChange, OnSave, and OnDelete. I have a GridView and work with its rows.

Can you help me and show me this code?


回答1:


Good article which can help you to achieve your task:

Custom Controls in Visual C# .NET

Step 1: Create the event handler in your control as below.

public event SubmitClickedHandler SubmitClicked;

// Add a protected method called OnSubmitClicked().
// You may use this in child classes instead of adding
// event handlers.
protected virtual void OnSubmitClicked()
{
    // If an event has no subscribers registered, it will
    // evaluate to null. The test checks that the value is not
    // null, ensuring that there are subscribers before
    // calling the event itself.
    if (SubmitClicked != null)
    {
        SubmitClicked();  // Notify Subscribers
    }
}

// Handler for Submit Button. Do some validation before
// calling the event.
private void btnSubmit_Click(object sender, System.EventArgs e)
{
    OnSubmitClicked();
}

Step 2 : Utilize the event in the page where you register your control. The following code is going to be part of your page where your control is registered. If you register it, it will be triggered by the submit button of the control.

// Handle the SubmitClicked Event
private void SubmitClicked()
{
    MessageBox.Show(String.Format("Hello, {0}!",
        submitButtonControl.UserName));
}


来源:https://stackoverflow.com/questions/10696651/define-custom-event-for-webcontrol-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!