兩個WebUserControl之間傳值

來源:互聯網
上載者:User

  兩個WebUserControl之間傳值,網上的代碼有,直接從UserControl1中定位到UserControl2的寫法,偶合性很強,感覺不太好,於是提供另外的寫法。

  用一個容器Container.aspx來放兩個WebUserControl,分別是UC1和UC2。現在假設要從UC1的一個事件觸發,把UC1中的一個值傳到UC2中。

1.新增一個Class,代碼如下:

 

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

//delegate要寫在共用class中,這樣的話,才可以讓PegatronEvent在不同的頁面都引用到。
public delegate void TreeViewEventHandler(object sender, PegatronEvent e);
public class PegatronEvent : EventArgs
{
    //構造函數
    public PegatronEvent()
    {
    }

    //聲明變數
    public string PegatronDeptId;

}

 

 

 

2.UC1中寫入事件

 

    //給這個usercontrol加一個event
    public event TreeViewEventHandler DeptInfoHandler;

    //TreeView的事件,當然用其他事件都OK。
    protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
    {
        PegatronEvent DeptEvent = new PegatronEvent();
        DeptEvent.PegatronDeptId = “我來傳東西”;
        //以下的事件裏面的參數是一定要寫的,sender可以是某個控制項的id,也可以是整個頁面(this);
        //DeptEvent也一定要,而且類型一定要是PegatronEvent,因為在App_Code/PegatronEvent.cs已經定義了。
        DeptInfoHandler(this, DeptEvent);
    }

 

 

3.在放兩個Usercontrol的頁面Container.aspx中加入代碼:

*這是整個過程的最關鍵點,相當於在兩個UserControl之間加一個橋樑。

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class UI_DepartContainer : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        UC1.DeptInfoHandler += new TreeViewEventHandler(UC1_DeptInfoHandler);
    }

    public void UC1_DeptInfoHandler(object sender, PegatronEvent e)
    {
        //取得UserControl的TreeView返回的部門代碼
        UC2.deptid = e.PegatronDeptId.ToString();
    }
}

 

4.在UC2中獲得值,不多說了,代碼如下:

 

    private string _deptid;

    public string deptid
    {
        get { return _deptid; }
        set 
        { 
            _deptid = value;
        }
    }

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.