CSDN博客

img goody9807

用例子说明怎样动态创建控件.

发表于2004/10/12 13:50:00  1788人阅读

因为之前有一段时间没有来,最近问这个的好象还是很多的.
所以特意写了个例子. (之前已经写过多次了,不过帖子都存档了)

没有多写注释,有问题的请问.

希望对你开发比较动态的控件有帮助.

<%@ Page Language=C# %>
<SCRIPT runat="server">

public class MyControl : Control , INamingContainer
{
 Button btn1;
 HyperLink link1;
 
 LinkButton btn2;
 HyperLink link2;

 override protected void CreateChildControls()
 {
  CreateControlsByType();
 }
 
 protected void CreateControlsByType()
 {
  object o=ViewState["type"];
  int t=o==null?1:(int)o;//默认是方案1
  
  if(t==1)
  {
   btn1=new Button();
   btn1.Text="切换到方案2";
   btn1.Click+=new EventHandler(btn1_Click);
   link1=new HyperLink();
   link1.NavigateUrl="http://www.asp.net";
   link1.Text="Link1";
   
   Controls.Add(new LiteralControl("<table border=1><tr><td>"));
   Controls.Add(btn1);
   Controls.Add(new LiteralControl("</td><td>"));
   Controls.Add(link1);
   Controls.Add(new LiteralControl("</td></tr></table>"));
  }
  else//方案2
  {
   btn2=new LinkButton();
   btn2.Text="切换到方案1";
   btn2.Click+=new EventHandler(btn2_Click);
   
   link2=new HyperLink();
   link2=new HyperLink();
   link2.NavigateUrl="http://www.microsoft.com";
   link2.Text="Link2";
   
   Controls.Add(new LiteralControl("<table border=1><tr><td>"));
   Controls.Add(btn2);
   Controls.Add(new LiteralControl("</td><td>"));
   Controls.Add(link2);
   Controls.Add(new LiteralControl("</td></tr></table>"));
  }
 }
 void EnsureRecreateControls()
 {
  if(ChildControlsCreated)
  {
   Controls.Clear();
   CreateControlsByType();
  }
  else
  {
   EnsureChildControls();
  }
 }
 
 void btn1_Click(object sender,EventArgs args)
 {
  ViewState["type"]=2;
  
  EnsureRecreateControls();
  
  link2.Text="已经切换为2方案了";
 }
 void btn2_Click(object sender,EventArgs args)
 {
  ViewState["type"]=1;
  
  EnsureRecreateControls();
  
  link1.Text="已经切换为1方案了";
 }
}

override protected void OnInit(EventArgs args)
{
 holder1.Controls.Add(new MyControl());
 base.OnInit(args);
}
</SCRIPT>
<html>
 <head>
  <title>Sample By Lostinet</title>
  <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
 </head>
 <body>
  <form id="SampleForm" method="post" runat="server">
   <asp:PlaceHolder Runat=server ID=holder1>
   </asp:PlaceHolder>
   <br/>
   <asp:Button Runat=server Text="在控件之外进行回发"></asp:Button>
  </form>
 </body>
</html>

阅读全文
0 0

相关文章推荐

img
取 消
img