目标页中获取文本框控件,并获取其Text属性值的代码如下:
if (this.PreviousPage != null) { TextBox UserNameTextBox = (TextBox)this.PreviousPage.FindControl("UserNameTextBox"); if (UserNameTextBox != null) { this.Response.Write(UserNameTextBox.Text); } } |
如果所要获取的控件位于某个控件的内部,比如下面的代码,UserNameTextBox控件位于名为UserPanel的Panel控件内部。那么首先找出这个Panel控件,然后通过此控件的FindControl()方法找出内部的文本框控件。
源页的源代码如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SourcePage.aspx.cs" Inherits="SourcePage" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>源页:通过控件属性传递数据!</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Panel ID="UserPanel" runat="server"> 用户名:<asp:TextBox ID="UserNameTextBoxInPanel" runat="server"></asp:TextBox> <br /> <asp:Button ID="SubmitButtonInPanel" runat="server" Text="提交到目标页" PostBackUrl="~/DestinationPage.aspx" /> </asp:Panel> </div> </form> </body> </html> |
目标页中获取这个位于Panel控件内部的TextBox控件的代码如下:
if (this.PreviousPage != null) { Panel UserPanel = (Panel)this.PreviousPage.FindControl("UserPanel"); if (UserPanel != null) { TextBox UserNameTextBox = (TextBox)UserPanel.FindControl("UserNameTextBoxInPanel"); if (UserNameTextBox != null) { this.Response.Write(UserNameTextBox.Text); } } } |
不管控件位于那个级别的命名容器控件内部,都是通过这种方式来获取的。
一定不要忘记判断所获取的控件引用是否为null。
到这里为止,5种在网页间传递数据的方式基本已经展示完毕!^_^