【发布时间】:2011-11-02 12:41:53
【问题描述】:
我在将变量从包含用户控件的主页传递到用户控件本身时遇到问题。虽然传递的变量通常在用户控件的代码隐藏中可用,但 page_load 事件似乎无法读取它。
我的代码 -
在主页面代码隐藏中:
protected void FindCCFsButton_Click(object sender, EventArgs e)
{
if (CustomerDropDown.SelectedIndex != 0)
{ SearchUcCCFList.SetCustID(CustomerDropDown.SelectedValue); }
}
(SearchUcCCFList 是主 aspx 页面中用户控件的实例)。 在用户控制代码后面:
public partial class ucCCFList : System.Web.UI.UserControl
{
public string srchCust { get; set; }
public void SetCustID(string custID)
{
srchCust = custID;
testCustLabel.Text = GetCustID(); //this works
}
public string GetCustID()
{
return srchCust;
}
protected void Page_Load(object sender, EventArgs e)
{
CCFGridView.DataSource = DAL.SearchCCFs(custID : GetCustID()); //doesn't work
CCFGridView.DataBind();
test2CustLabel.Text = GetCustID(); //doesn't work
}
在 Page_Load 事件中,GetCustId() 不返回任何内容(因此记录不会被过滤并且全部返回),尽管它可以在 Page_Load 之外的方法中读取。
我可能犯了初学者的错误,但我们将不胜感激。
编辑 - 按照 Alan 在 cmets 中的建议,我逐步完成了页面加载顺序,并且用户控件的 Page_Load 事件似乎在主页面按钮中的代码单击之前运行,因此该变量尚不可用。点击按钮后的顺序为:
- 用户控件Page_Load运行
- 主页按钮事件中的代码
- 用户控件中的其他代码(Page_Load 之外)运行,因此此处提供了变量。
这似乎有点奇怪,有没有其他方法可以将变量传递给用户控件Page_Load?
【问题讨论】:
-
你从哪里打电话给
SearchUcCCFList.SetCustID?必须在页面的Page_Load之前或之中 -
我不认为 GetCustID 方法有帮助..您可以从属性中提取属性的值吗?看起来页面事件生命周期顺序是一个问题。一些断点将帮助您了解发生了什么。
-
Tim - SearchUcCCFList.SetCustID 位于主页上的按钮单击事件中(即其中包含用户控件(id=SearchUcCCFList)的事件)。我已将其添加到帖子中。
-
Alan - 第一个测试标签只是显示正在从主页接收 SetCustID 的值,尽管在 Page_Load 事件中无法读取它。我遵循了您关于断点的建议并将结果添加到原始帖子中。
标签: asp.net user-controls scope