用户控件 之 访问用户控件中的控件

1.用户控件
WebUserControl.ascx
<% @ Control Language = " C# "  AutoEventWireup = " true "  CodeFile = " WebUserControl.ascx.cs "  Inherits = " WebUserControl "   %>
< asp:Label  ID ="Label1"  Text ="Mzwu.Com"  runat ="server"  Height ="20px"  Width ="226px" ></ asp:Label >
< asp:Label  ID ="Label2"  runat ="server"  Text ="Hello World!"  Height ="20px"  Width ="226px" ></ asp:Label >
 
WebUserControl.ascx.cs
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  WebUserControl : System.Web.UI.UserControl
{
    
public   string  Message
    {
        
get  {  return  Label1.Text; }
    }
}
 

2.访问用控件里面的控件

Default.aspx:
 
<% @ Page Language = " C# "  AutoEventWireup = " true "  CodeFile = " Default.aspx.cs "  Inherits = " _Default "   %>

<% @ Register Src = " WebUserControl.ascx "  TagName = " WebUserControl "  TagPrefix = " MyControl "   %>

<! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >

< html  xmlns ="http://www.w3.org/1999/xhtml"   >
< head  runat ="server" >
    
< title > 访问用户控件中的控件-Mzwu.Com </ title >
</ head >
< body >
    
< form  id ="form1"  runat ="server" >
    
< div >
        
< MyControl:WebUserControl  ID ="WebUserControl1"  runat ="server"   />
    
</ div >
    
</ form >
</ body >
</ html >
 
 
Default.aspx.cs
 
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 _Default : System.Web.UI.Page
{
    
protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write(WebUserControl1.Message);
//方法一:使用属性访问
        Response.Write(((Label)WebUserControl1.FindControl("Label2")).Text);//使用FindControl方法
    }
}

本文出自 “跟着兴趣走” 博客,谢绝转载!

你可能感兴趣的:(职场,休闲,用户控件)