c# - 无法访问 asp :TextBox tag from the C# file : the name 'txtUsername' does not exist in the current context

标签 c# asp.net .net visual-studio-2012 visual-studio-2013

考虑 aspx :

CS.aspx :

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CS.aspx.cs" Inherits="CS" %>

<!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>
    <style type="text/css">
        body
        {
            font-family: Arial;
            font-size: 10pt;
        }
        input
        {
            width: 200px;
        }
        table
        {
            border: 1px solid #ccc;
        }
        table th
        {
            background-color: #F7F7F7;
            color: #333;
            font-weight: bold;
        }
        table th, table td
        {
            padding: 5px;
            border-color: #ccc;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <table border="0" cellpadding="0" cellspacing="0">
        <tr>
            <th colspan="3">
                Registration
            </th>
        </tr>
        <tr>
            <td>
                Username
            </td>
            <td>
                <asp:TextBox ID="txtUsername" runat="server" />
            </td>
            <td>
                <asp:RequiredFieldValidator ErrorMessage="Required" ForeColor="Red" ControlToValidate="txtUsername"
                    runat="server" />
            </td>
        </tr>
        <tr>
            <td>
                Password
            </td>
            <td>
                <asp:TextBox ID="txtPassword" runat="server" TextMode="Password" />
            </td>
            <td>
                <asp:RequiredFieldValidator ErrorMessage="Required" ForeColor="Red" ControlToValidate="txtPassword"
                    runat="server" />
            </td>
        </tr>
        <tr>
            <td>
                Confirm Password
            </td>
            <td>
                <asp:TextBox ID="txtConfirmPassword" runat="server" TextMode="Password" />
            </td>
            <td>
                <asp:CompareValidator ErrorMessage="Passwords do not match." ForeColor="Red" ControlToCompare="txtPassword"
                    ControlToValidate="txtConfirmPassword" runat="server" />
            </td>
        </tr>
        <tr>
            <td>
                Email
            </td>
            <td>
                <asp:TextBox ID="txtEmail" runat="server" />
            </td>
            <td>
                <asp:RequiredFieldValidator ErrorMessage="Required" Display="Dynamic" ForeColor="Red"
                    ControlToValidate="txtEmail" runat="server" />
                <asp:RegularExpressionValidator runat="server" Display="Dynamic" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
                    ControlToValidate="txtEmail" ForeColor="Red" ErrorMessage="Invalid email address." />
            </td>
        </tr>
        <tr>
            <td>
            </td>
            <td>
                <asp:Button Text="Submit" runat="server" OnClick="RegisterUser" />
            </td>
            <td>
            </td>
        </tr>
    </table>
    </form>
</body>
</html>

及其 C# 文件:CS.asps.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;

public partial class CS : System.Web.UI.Page
{
    protected void RegisterUser(object sender, EventArgs e)
    {
        int userId = 0;
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("Insert_User"))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@Username", txtUsername.Text.Trim());
                    cmd.Parameters.AddWithValue("@Password", txtPassword.Text.Trim());
                    cmd.Parameters.AddWithValue("@Email", txtEmail.Text.Trim());
                    cmd.Connection = con;
                    con.Open();
                    userId = Convert.ToInt32(cmd.ExecuteScalar());
                    con.Close();
                }
            }
            string message = string.Empty;
            switch (userId)
            {
                case -1:
                    message = "Username already exists.\\nPlease choose a different username.";
                    break;
                case -2:
                    message = "Supplied email address has already been used.";
                    break;
                default:
                    message = "Registration successful.\\nUser Id: " + userId.ToString();
                    break;
            }
            ClientScript.RegisterStartupScript(GetType(), "alert", "alert('" + message + "');", true);
        }
    }
}

当我尝试编译时,我得到了这个:

enter image description here

The name 'txtUsername' does not exist in the current context

The name 'txtPassword' does not exist in the current context

The name 'txtEmail' does not exist in the current context

知道为什么会这样吗? txtUsername.aspx 文件中声明。

最佳答案

问题出在文件的声明上。它应该看起来像:

<%@ Page Language="C#" 
       AutoEventWireup="true" 
       CodeBehind="CS.aspx.cs" 
       Inherits="CS" %>

它是 .designer.cs 文件,其中包含供 .cs 文件使用的 aspx 对象的定义。

通过指定 CodeFile,您表示您正在使用网站项目类型文件而不是 WebForm。

指定 CodeBehind 而不是 CodeFile,这将允许 VS 将定义添加到 .designer.cs 文件。

编辑:

如果您没有 .designer 文件,您可以通过以下方式创建:

  1. 打开CS.aspx所在的目录。
  2. 新建一个文本文件,命名为CS.aspx.designer.cs
  3. 在 Visual Studio 中显示项目中的所有文件
  4. 深入到 CS.aspx.cs,您将看到您的文件。
  5. 将其包含在项目中。
  6. 更改 CS.aspx 文件中的内容并保存。

这会将您的文件转换为 Webform 文件。

看起来@mellamokb 也有同样的想法。 :)

关于c# - 无法访问 asp :TextBox tag from the C# file : the name 'txtUsername' does not exist in the current context,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23479204/

相关文章:

.net - .NET 异常类型的 _xcode 字段是什么?

c# - 使用 XML 作为小型 C# 应用程序的数据持久性的好方法是什么?

c# - 对象名称 'dbo.UserNotes' 无效。异常 - ASP.NET MVC 4

c# - 将 Unity texture2d 转换为 ffmpeg 的 YUV420P

c# - 缓存项永不过期

c# - 将派生类添加到 DataGridView 的绑定(bind)源

c# - 如何在 Azure App Service 上运行的 ASP.NET Framework App 中禁用服务器 GC

c# - ValidationGroup 并有效地验证多个文本框 asp c#

c# - TFS API 是否需要 Visual Studio?

c# - 如何将枚举值设置为 Web 用户控件的自定义属性?