简体   繁体   English

从asp.net中的上一页读取控件

[英]Reading controls from previous page in asp.net

I have Page1.aspx containing 我有Page1.aspx包含

Name: <asp:TextBox ID="txt1" runat="server" />

Page2.aspx tries to access its contents by Page2.aspx尝试通过以下方式访问其内容

   TextBox txt2 = (TextBox)PreviousPage.FindControl("txt1");

However I end up getting an Object reference not set to instance of an object exception 但是我最终得到的对象引用未设置为对象异常的实例

I've used PreviousPage before and have had success with this snippet of code I found elsewhere online (Can't remember where I found it!) 我以前使用过PreviousPage ,并且在网上其他地方找到的这段代码片段都取得了成功(不记得在哪里找到了!)

So.. 所以..

Option 1: 选项1:

On your first page you have your button that takes you to the second page, you need to set the PostBackUrl property to the new page url: 在第一页上,您具有将您带到第二页的按钮,您需要将PostBackUrl属性设置为新的页面URL:

<asp:Button ID="button1" Runat="server" Text="submit" PostBackUrl="~/Page2.aspx" />

( This is presuming that your 1st page is a form that redirects to your Page2.aspx ) 这是假定您的第一页是重定向到Page2.aspx的表单

Then in the new page's code behind you need to write something along the lines of this: 然后,在新页面的后面代码中,您需要按照以下内容编写代码:

public void page_load()
{
if(!IsPostBack)
{
TextBox tb = (TextBox)PreviousPage.FindControl("txt2");
Response.Write(tb.Text);}
}

You will need to transfer the value of the previous page's txt2.Text to a textbox or label on the new page if you are wanting to do any more postbacks on the second page, otherwise you will lose that value. 如果您想在第二页上进行更多的回发,则需要将前一页的txt2.Text的值转移到新页上的文本框或标签上,否则将丢失该值。

Option 2: 选项2:

You could also use a Session variable surely to store your data?! 您还可以肯定使用Session变量来存储数据吗?

Session["text"] = txt2.Text;

一旦您进入了新页面,最后一页可能就不见了,建议您在会话中传输数据。

Are you referring to ASP.NET 2.0 Wizard Control ? 您是指ASP.NET 2.0向导控件吗? An example is in the link. 链接中有一个示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM