0

我有一个 asp.net 页面,客户可以在其中在文本字段中插入输入:

<table>
    <tr>
        <td style="width: 56px"><asp:Label ID="Label1" runat="server" Text="Name"></asp:Label></td>
        <td style="width: 148px"><asp:TextBox ID="name" runat="server" Width="272px"></asp:TextBox></td>
    </tr>

    <tr>
        <td style="width: 56px"><asp:Label ID="Label2" runat="server" Text="Email"></asp:Label></td>
        <td style="width: 148px"><asp:TextBox ID="email" runat="server" Width="272px"></asp:TextBox></td>
    </tr>

    <tr>
        <td style="width: 56px"><asp:Label ID="Label3" runat="server" Text="Subject"></asp:Label></td>
        <td style="width: 148px"><asp:TextBox ID="sub" runat="server" Width="272px"></asp:TextBox></td>
    </tr>

    <tr>
        <td style="width: 56px"><asp:Label ID="Label4" runat="server" Text="Message"></asp:Label></td>
        <td style="width: 148px">
            <asp:TextBox ID="message" runat="server" Width="272px"></asp:TextBox>
            <!--<textarea id="message"; cols="1"; rows="1"; style="width: 272px; height: 152px;"></textarea>-->
        </td>
    </tr>
    <tr></tr>
    <tr>
        <td style="width: 56px; height: 36px;"></td>
        <td style="width: 148px; height: 36px;"><asp:Button ID="Button1" runat="server" Text="Submit" Style="float:left" OnClick="Button1_Click" />
            <asp:Button ID="Button2" runat="server" Text="Reset" />
            <asp:button id="btnTest" runat="server" onclick="btnTest_Click" text="Test Database Connection" />
        </td>
    </tr>
</table>      "

我有一个方法试图将我的值添加到数据库中:

protected void Button1_Click(object sender, EventArgs e)
{
    using (SqlConnection conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
    {
        //Check if the same request is already submitted.

        SqlCommand cmd1 = new SqlCommand();
        cmd1.CommandType = System.Data.CommandType.StoredProcedure;
        cmd1.CommandText = "dbo.Procedure";

        cmd1.Parameters.Add("@name", System.Data.SqlDbType.VarChar).Value = name.Text;
        cmd1.Parameters.Add("@email", System.Data.SqlDbType.VarChar).Value = email.Text;
        cmd1.Parameters.Add("@sub", System.Data.SqlDbType.VarChar).Value = sub.Text;
        cmd1.Parameters.Add("@message", System.Data.SqlDbType.VarChar).Value = message.Text;

        cmd1.Connection = conn1;
        conn1.Open();
        cmd1.ExecuteNonQuery();
        conn1.Close();
    }                 
    Response.Redirect("~/Default.aspx");     
}

但现在我收到类似“名称'name'/'email'/'sub'/'message'在当前上下文中不存在”的错误。我是 .net 框架和 C# 的新手。请帮忙。

我的起始页是 Default.aspx,提交按钮在 Contact.aspx 页面上。但是当我在设计模式下按下提交按钮时,在 Default.aspx.cs 后面的代码中创建的方法。会不会是个问题?

4

1 回答 1

1

对我来说,后面的代码似乎无法找到带有 ID(电子邮件、姓名...)的文本框。如果您正在使用 Web 应用程序项目,请检查您的 .aspx.designer.cs 文件以确保它已正确初始化。此外,部分类名和命名空间后面的代码必须与您的 aspx 页面中 <%@ Page ... %> 指令中的 Inherits="xxx" 属性匹配。但是,您也可能遇到此问题,因为您的表位于某些数据绑定或动态控件中,在这种情况下,您必须在代码中查找控件引用。

于 2012-06-19T22:29:36.333 回答