在没加载成功是不能对它设置属性的,以免带来不别要的错误!!
代码如下:
Default.aspx
1using System;
2using System.Data;
3using System.Configuration;
4using System.Web;
5using System.Web.Security;
6using System.Web.UI;
7using System.Web.UI.WebControls;
8using System.Web.UI.WebControls.WebParts;
9using System.Web.UI.HtmlControls;
10using System.Drawing;
11public partial class _Default : System.Web.UI.Page
12{
13
14
15
16 protected void Page_Load(object sender, EventArgs e)
17 {
18
19
20 Control control = LoadControl("~/myControl.ascx"); //加载用户控件
21 this.Panel1.Controls.Add(control); //把它添加到该面板中
22
23
24 myControl myC = control as myControl; //获得实例
25 if (myC == null) //是否用户控件加载成功
26 {
27 PartialCachingControl pcc = control as PartialCachingControl;
28 if (pcc != null) myC = pcc.CachedControl as myControl;
29 }
30 if (myC != null) myC.BackColor = Color.Yellow; //成功设置该控件的样式
31
32
33 }
34}
35
1using System;
2using System.Data;
3using System.Configuration;
4using System.Collections;
5using System.Web;
6using System.Web.Security;
7using System.Web.UI;
8using System.Web.UI.WebControls;
9using System.Web.UI.WebControls.WebParts;
10using System.Web.UI.HtmlControls;
11using System.Drawing;
12
13public partial class myControl : System.Web.UI.UserControl
14{
15 public Color BackColor
16 {
17 get { return TextBox1.BackColor; }
18 set { TextBox1.BackColor = value; }
19 }
20
21 protected void Page_Load(object sender, EventArgs e)
22 {
23 TextBox1.Text = DateTime.Now.ToLongTimeString();
24 }
25
26 protected void Button1_Click(object sender, EventArgs e)
27 {
28 this.TextBox2.Text = this.TextBox1.Text;
29 }
30}
31