我正在尝试制作一个将数据发布到另一个网络表单的 asp 网络表单。
我做了两个独立的项目,一个使用母版页,一个不使用。
塞纳里奥:
WebForm1.aspx有两个文本框和一个提交按钮
<table>
<tr>
<td >Name:</td>
<td >
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
<td class="auto-style1"></td>
</tr>
<tr>
<td>Id:</td>
<td>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</td>
<td> </td>
</tr>
<tr>
<td> </td>
<td>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</td>
<td> </td>
</tr>
</table>
WebForm2.aspx.cs有两个标签,它们应该显示从 WebForm1.aspx 接收到的数据
Page prevPage = this.PreviousPage;
if (prevPage != null)
{
Label1.Text = ((TextBox)prevPage.FindControl("TextBox1")).Text;
Label2.Text = ((TextBox)prevPage.FindControl("TextBox2")).Text;
}
案例一:【无母版页发帖】
数据正常发布。
案例 2:[使用母版页发布]
我得到NullReferenceException。
所以我分解了代码。
Page prevPage = this.PreviousPage;
if (prevPage != null)
{
ControlCollection collec = prevPage.Controls;
Control ctrl= prevPage.FindControl("TextBox1");
TextBox txtbx = (TextBox)ctrl;
Label1.Text = txtbx.Text; //Exception raised here
Label2.Text = ((TextBox)prevPage.FindControl("TextBox2")).Text;
}
调试时:我在即时窗口中执行了“collec.Count”。
案例一:【无母版页发帖】
colec.Count 返回5
案例 2:[使用母版页发布]
colec.Count 返回1 [ 为什么?]
之后,
我尝试使用公共属性传递数据
WebForm1.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Server.Transfer("WebForm2.aspx");
}
public string Name { get { return TextBox1.Text; } }
public string ID { get { return TextBox2.Text; } }
WebForm2.aspx.cs
WebForm1 prevPage = (WebForm1)this.PreviousPage;
if (prevPage != null)
{
ControlCollection c = prevPage.Controls;
Label1.Text = prevPage.Name;
Label2.Text = prevPage.ID;
}
现在它可以正常工作,即使是母版页。
那么谁能解释我发生了什么以及为什么从一个内容页面发布到另一个内容页面而主人给我 NullReferenceException ?