BloggerAds

2011年8月29日 星期一

UserControl 提供事件給網頁(Parent Page)觸發的方式

最近在弄一個讓 UserControl 提供事件給網頁呼叫的東西下面就提供一個範例,來讓UserControl中的 GridView的 RowSelecting 事件提供給網頁(Parent Page)觸發

1.首先,在UserControl的ascx.cs中,宣告一個事件:
public event EventHandler PublicRowSelecting;
2.再來還是在UserControl的ascx.cs中,讓原本的GridView RowSelecting的事件,執行剛剛宣告的事件PublicRowSelecting:
protected void gvMain_RowSelecting(object sender, GridViewSelectEventArgs e) {                             
            this.PublicRowSelecting(this, new EventArgs());       
}
3.接下來就是在網頁中使用了,在網頁(Parent Page)的aspx.cs 直接設定事件
UserControl1.PublicRowSelecting += new EventHandler(UserControl1_PublicRowSelecting);
4. UserControl1_PublicRowSelecting 是你要執行的程式,這個範例只要 Response.Write就好了

protected void UserControl1_PublicRowSelecting(object sender, EventArgs e) {
      Response.Write("Test OK");
}
5.大功告成,接下來只要執行到 UserControl中GridView的RowSelecting事件,就會執行UserControl1_PublicRowSelecting了。

沒有留言:

張貼留言