1.从页面向用户控件交换信息,代码写在页面中

法1:使用FindControl("用户控件中的控件的ID")

    //法1
    protected void Button1_Click(object sender, EventArgs e)
    {
        string s = txt.Text;
        TextBox textbox1 = WUC1.FindControl("TextBox1") as TextBox;//强转
        textbox1.Text = s;
    }

法2:事先在用户控件中定义public属性,通过属性为里面的控件赋值或取值

//用户控件中的代码

public string TextValue
    {
        get
        {
            return TextBox1.Text;
        }
        set
        {
            TextBox1.Text = value;
        }
    }

//页面中的代码

    //法2
    protected void Button2_Click(object sender, EventArgs e)
    {
        WUC1.TextValue = txt.Text;
    }

2.从用户控件向页面交换信息,代码要写在用户控件中

法1:session

 第一步:在用户控件的按钮中把数据放在Session中

    protected void Button1_Click(object sender, EventArgs e)
    {
        //把数据放在session中
        string x = TextBox1.Text;
        Session["data"] = x;
    }

第二步:在页面的override OnLoadComplete事件中,从Session中取出数据来,显示在页面上

    protected override void OnLoadComplete(EventArgs e)
    {
        base.OnLoadComplete(e);
        if (Session["data"] != null)
        {
            Label1.Text = Session["data"].ToString();
        }
    }

法2:代理/委托  delegate - 指向方法(动作)的引用

代理的使用步骤:
第一步: 使用 delegate 定义一个新的代理类型。
public delegate 返回类型 代理类型名( 参数定义);
例如:public delegate void ShowDelegate(string s);
第二步:使用新的代理类型定义一个变量(代理变量)
ShowDelegate Show;
第三步:把代理变量指向一个新的方法
Show = new ShowDelegate(方法名);
第四步:通过调用代理来实现对方法的调用。
Show("hello");

 

用户控件:

    //1.在用户控件中声明代理类型
    public delegate void ShowDelegete(string s);//返回空接收字符串的方法

    //2.定义代理变量
    public ShowDelegete Show;
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    //点按钮
    protected void Button1_Click(object sender, EventArgs e)
    {
        //4.调用代理
        if (Show != null)//如果不为空
        {
            string x = TextBox1.Text;
            Show(x);//调用Show,接收字符串
        }
    }

页面:

    protected void Page_Load(object sender, EventArgs e)
    {
        //3.让代理指向方法
        TextUC1.Show = new TextUC.ShowDelegete(SetValue);
    }

    //定义一个方法
    private void SetValue(string s)
    {
        TextBox1.Text = s;//页面的文本框
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        //让代理指向方法
        TextUC1.Show = new TextUC.ShowDelegete(SetValue);
    }

    //定义一个方法
    private void SetValue(string s)
    {
        Label1.Text = s;
    }

 

 

 



 

posted on 2015-08-26 11:26  浅笑瑾年  阅读(182)  评论(0编辑  收藏  举报