1

所以我假设这与页面生命周期有关,也许控件尚未绑定到页面加载?老实说,我仍在学习 ASP.NET 页面生命周期,何时发生绑定,何时可以访问某些数据以及何时太早/太晚等等。我只是想很好地解释一下为什么以下内容不起作用. 假设一个递归搜索控件的方法,从一个RepeaterItem开始,寻找一个TextBox,就像这样......

 private void FindMyTextBox()
 {
    foreach (RepeaterItem repeated in myRepeater.Items)
    {
        TextBox txtPercentage = (TextBox)FindControlRecursive(repeated, "txtPercentage");
        .
        .
        .
    }
 }

....在哪里....

public static Control FindControlRecursive(Control root, string id)
{
    if (root.ID == id)
    {
        return root;
    }

    return root.Controls.Cast<Control>()
        .Select(c => FindControlRecursive(c, id))
        .FirstOrDefault(c => c != null);
}

...为什么会从绑定到OnClick事件的方法中调用这项工作,例如....

<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="Validate" />

 protected void Validate(object sender, EventArgs e)
 {
     FindMyTextBox();
 }

...但不是从 Page_Load 调用时,例如....

protected void Page_Load(object sender, EventArgs e)
{
    FindMyTextBox();
}
4

0 回答 0