2014-05-01 47 views
9

我正在用asp.net和C#編程語言創建一個登錄系統。處理用戶和密碼的代碼已完成。但在視圖層,我很煩惱從用戶名文本框和密碼文本框中獲取值並將其傳遞給代碼隱藏。Asp.net從aspx中的文本框中獲取值到後面的代碼

這兩個文本框都是ID標識的,在我的編程技巧方面,一個ID應該足以訪問這些元素。

這是我的aspx登錄頁面:

<asp:Login ID="Login1" runat="server" ViewStateMode="Disabled" RenderOuterTable="false"> 
     <LayoutTemplate> 
      <p class="validation-summary-errors"> 
       <asp:Literal runat="server" ID="FailureText" /> 
      </p> 
      <fieldset> 
       <legend>Log in Form</legend> 
       <ol> 
        <li> 
         <asp:Label ID="Label1" runat="server" AssociatedControlID="UserName">User name</asp:Label> 
         <asp:TextBox runat="server" ID="UserName" /> 
         <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="UserName" CssClass="field-validation-error" ErrorMessage="The user name field is required." /> 
        </li> 
        <li> 
         <asp:Label ID="Label2" runat="server" AssociatedControlID="Password">Password</asp:Label> 
         <asp:TextBox runat="server" ID="Password" TextMode="Password" /> 
         <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="Password" CssClass="field-validation-error" ErrorMessage="The password field is required." /> 
        </li> 
        <li> 
         <asp:CheckBox runat="server" ID="RememberMe" /> 
         <asp:Label ID="Label3" runat="server" AssociatedControlID="RememberMe" CssClass="checkbox">Remember me?</asp:Label> 
        </li> 
       </ol> 
       <asp:Button ID="Button1" runat="server" CommandName="Login" Text="Log in" OnClick="Button1_Click"/> 
      </fieldset> 
     </LayoutTemplate> 
    </asp:Login> 

該我做的用戶名和密碼文本框獲取值:

  1. 使用代碼:

    string user = this.UserName.Text; 
    string pass = this.Password.Text; 
    
  2. 使用代碼:

    Textbox UserName = this.FindControl("UserName"); 
    
  3. 刪除aspx.design.cs並右鍵單擊表單並將其轉換爲應用程序;

  4. 在設計中添加的代碼下面幾行:

    protected global::System.Web.UI.WebControls.TextBox UserName; 
    protected global::System.Web.UI.WebControls.TextBox Password; 
    

毫無效果,到目前爲止,當我到達這條線:

string user = this.UserName.Text; 

這引發了我一個錯誤:

Object Reference not set an instance of an object.

你可以嗎對我的問題提出任何解決方案?

回答

10

這是因爲這些控件是模板的一部分。它們不是直接在頁面上,當Login控制被初始化時,它們被動態地添加到那裏。要訪問它們,您需要FindControl

string user = ((TextBox)Login1.FindControl("UserName")).Text; 
+0

It Worked!非常感謝!! – VCore

相關問題