关于asp.net用户控件

1. 如何动态加载用户控件。经常会遇到这样的问题,需要根据输入的参数来决定是否或者是加载哪一个ascx,也就是ms所说的用编程的方式加载用户控件。
常用的做法是在aspx加一个PlaceHolder---VoteControlPH,
 private void LoadVoteControl()
  {
     Control  voteControl = (UserControl)LoadControl("Vote.ascx");
     voteControl.ID = "VotePanel";
     VoteControlPH.Controls.Add(voteControl); 
  }
2.动态加载用户控件的时会出现事件丢失的现象。
这是因为事件触发时,LoadVoteControl不被重新执行,如果在
 private void Page_Load(object sender, System.EventArgs e)
 {
 if( !Page.IsPostBack )
   {LoadVoteControl();}
}
则会发生这样的情况,正确的做法是将LoadVoteControl的调用放在IsPostBack 之外。
对于这种情况,CSDN上的思归有详细的说明
http://blog.joycode.com/saucer/posts/19456.aspx
3.如何给用户控件传递参数。
常用做法 在ascx中定义属性,在aspx中创建ascx实例,并给属性赋值。这样做,在ascx中触发事件时,如果还要用到这些属性的值,就会发现属性值已经丢了。原因很简单,因为每个事件的触发都是一次向服务端提交的过程,提交后重新执行ascx.cs,属性值被初始化了。
我用了一个比较笨的方法,用viewstate来存储这些值,不知道还有没有更好的方法?
4.用户控件中调用aspx的事件和方法。
要这样做的话,首先,需要在ascx中定义事件的委托说明,看下面的例子:
ascx.cs:
  public delegate void myEventHandle();
  public event myEventHandle myEvent;

 //VoteShowLT是个linkbutton
  private void VoteShowLT_Click(object sender, System.EventArgs e)
  {
   if(myEvent != null) // 可能控件在页面上没定义事件
    myEvent();
   return;
  }

aspx.cs:
  private void InitializeComponent()
  {
....
   this.VotePanel.myEvent += new control.Vote.myEventHandle(this.BindData);
....
  }

这样,点击ascx中的VoteShowLT就可以触发aspx中的BindData的方法了。

5。用户控件支持嵌套调用,调用方法和apsx调用ascx一样。

posted @ 2004-04-20 09:31  9527的晃悠人生  阅读(1135)  评论(0编辑  收藏  举报