代码之家  ›  专栏  ›  技术社区  ›  Pauli Østerø

数据绑定属性并获取它们的值(ASP.Net)

  •  1
  • Pauli Østerø  · 技术社区  · 15 年前

    public class test : UserControl {
       public int Count { get; set; }
    
       public test() { 
          Count = 3;
       }
    
       public override DataBind() {
          aRepeater.DataSource = dal.GetObjects(Count);
    
          base.DataBind();
       }
    }
    

    我在我的页面上这样使用它

    <my:test runat="server" Count="<# something %>" />
    

    我现在的问题是,在调用base.DataBind()之前和之后,我无法在usercontrol中获取Count的值。我想这是一种将数据绑定到自身的方式。迄今为止的解决办法是:

    public override DataBind() {
       base.DataBind(); // to bind values to self
    
       aRepeater.DataSource = dal.GetObjects(Count);
    
       base.DataBind(); // to bind new values that is dependent on the the first bind
    }
    

    这是可行的,但似乎不对。因此,我的问题是,对于这种情况,最佳做法是什么。

    3 回复  |  直到 13 年前
        1
  •  1
  •   Eran Betzalel    15 年前

    这是有道理的,因为 Count="<# something %>" 发生在 DataBind() 数据绑定() 在这种情况下(不要使用页面绑定方法)。当然,这只是美化代码的问题——仅此而已。

        2
  •  1
  •   thorn0    15 年前

    protected override void OnDataBinding(EventArgs e) {
        base.OnDataBinding(e);
        aRepeater.DataSource = dal.GetObjects(Count);
    }
    

    DataBind方法基本上由两个步骤组成:1)OnDataBinding(),2)每个子控件的DataBind()。

        3
  •  0
  •   James Lawruk    15 年前

    是否必须在.ascx文件中设置用户控件的Count属性?在包含用户控件的页面的代码隐藏中完全没有Count属性或设置Count如何?

     <my:test runat="server" id="test1" />
    

    //User control code behind.  GetCount() returns an int.
    public override DataBind() {
    
        aRepeater.DataSource = dal.GetObjects(GetCount());   
        base.DataBind(); 
    }
    

    //Page that has the user control. 
    protected void Page_Load(object sender, EventArgs e)
    {
        this.test1.Count = 5;        
    }
    
    //User control code behind.
    public override DataBind() 
    {           
        aRepeater.DataSource = dal.GetObjects(this.Count);   
        base.DataBind(); 
    }