且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

页面加载后如何向ASP.NET控件添加事件?

更新时间:2023-12-06 10:19:10

如果在自定义控件上创建该事件,则无需检查该事件是否在页面上存在.如果确实如此,它将一定会触发该事件.还是我在这里想念东西?

If you create that event on the custom control, you won't need to check if it exists on the page or not. If it does, it will definately trigger the event. Or am I missing something here?



您需要做的是在控件上声明一个公共事件,然后当SelectedIndexChanged事件被触发时,您将触发该事件并在页面上接收它.

What you'll have to do is declare a public event on your control, then when the SelectedIndexChanged Event fired, you'd fire that event, and receive it on the page.

因此,在您的控制下,您将拥有:

So on your control you'd have:

public delegate void MyIndexChangedDelegate(string value);
public event MyIndexChangedDelegate MyEvent;

protected void myDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
    MyEvent(myDropDown.SelectedValue); // Or whatever you want to work with.
}

然后在页面上的控件声明中,您将拥有:

Then on your page, on your control declaration you'd have:

<usc:control1 runat="server" OnMyEvent="EventReceiver" />

以及后面的代码:

protected void EventReceiver(string value)
{
    // Do what you have to do with the selected value, which is our local variable 'value'
    ClientScript.RegisterStartupScript(typeof(Page), "Alert", string.Format("<script language='JavaScript'>alert('User selected value {0} on my DropDown!');</script>"), value);
}

应该可以.