我需要将自定义控件中的3个事件定义为OnChange
,OnSave
和OnDelete
。
我有GridView
并使用其行。
你能帮助我并告诉我这段代码吗?
答案 0 :(得分:11)
可以帮助您完成任务的好文章:
Custom Controls in Visual C# .NET
第1步:在控件中创建事件处理程序,如下所示。
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();
}
第2步:利用您注册控件的页面中的事件。以下代码将成为您的控件注册页面的一部分。如果您注册它,它将由控件的提交按钮触发。
// Handle the SubmitClicked Event
private void SubmitClicked()
{
MessageBox.Show(String.Format("Hello, {0}!",
submitButtonControl.UserName));
}