在Code-Behind中操作WebUserControl

 

首先,建立一個名稱為WebPlaceHolder.aspxPage.

WebPlaceHolder.aspx中添加一個PlaceHolder控件.

PlaceHolder控件就是: 動態儲存 Web 網頁上加入的WebUserControl.

(重點就在使用PlaceHolder控件)

其次,在加入一個名稱為WebUserControl1.ascx WebUserControl.

WebUserControl1.ascx中添加如下代碼:


WebUserControls1.ascx

using System;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebPlaceHolder
{
    
public class WebUserControl1 : UserControl
   
{
        
protected Button Button1;
        
protected Label Label1;
        
//定義一個屬性,用來設定Label1的Text屬性.
      public string TestString
       
{
           
set
            
{
                Label1.Text 
= value;
            }

        }

        
//將Button1_Click事件的聲明修改為Public,這樣才可以在外部調用
        public  void Button1_Click(object sender, EventArgs e)
        
{
            
this.Label1.Text ="User Controls is OK!";
        }

    }

}

WebPlaceHolder.cs
using System;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebPlaceHolder
{
public class WebForm1 : Page
{

        
protected PlaceHolder PlaceHolder1;
        
protected Button Button1;
        
public WebUserControl1 wuc ;
    
        
private void Page_Load(object sender, EventArgs e)
       
{
            
//得到WebUserControl1的對象
           
wuc = (WebUserControl1)LoadControl("WebUserControl1.ascx");
           
//給wuc的TestString屬性付值.
            wuc.TestString="test ok";   
            
//將wuc添加到PlaceHolder1中
            this.PlaceHolder1.Controls.Add(wuc);
        }

    
private void Button1_Click(object sender, EventArgs e)
     
{
            
//調用wuc中的事件.事件只有聲明為Public才可以被使用
            this.wuc.Button1_Click(sender,e);
        }

    }

}

posted @ 2004-11-25 11:14  Vincent  阅读(1453)  评论(2编辑  收藏  举报