我们可以举个最简单的例子,user control封装一个textbox,并且做一个wrapper来包装textbox的值
public partial class WebUserControl1 : System.Web.UI.UserControl
{
private string textBoxValue;
public string TextBoxValue {
get {
return textBoxValue;
}
set {
textBoxValue = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
我们想在Page:Page_Load中访问到user control封装的值
这里会有两个问题
1. 首先,看下page与User control的加载顺序
User Control:OnInit
User Control:Page_Init
Page:OnInit
Page:Page_Init
Page:Page_Load
User Control:Page_Load
User Control加载Page_Load晚于Page
那么,我们只能在User Control:OnInit或者User Control:Page_Init中封装textbox的值
2. 其次
在User Control:OnInit和User Control:Page_Init中, textbox的值都是空
像这种情况,不得不使用Request.Form来取值,最原始的办法,也是最管用的,代码如下
public partial class WebUserControl1 : System.Web.UI.UserControl
{
private string textBoxValue;
public string TextBoxValue {
get {
return textBoxValue;
}
set {
textBoxValue = value;
}
}
protected void Page_Init(object sender, EventArgs e)
{
if (Request.Form[TextBox1.UniqueID.ToString()] == null)
{
TextBoxValue = "";
}
else {
TextBoxValue = Request.Form[TextBox1.UniqueID.ToString()].ToString();
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
}