System.Data.SqlClient.SqlException:'必须声明标量变量“ @TxtTitle”。'

时间:2020-06-30 12:30:05

标签: javascript jquery asp.net sql-server webforms

点击提交按钮后,出现以下错误:System.Data.SqlClient.SqlException: 'Must declare the scalar variable "@TxtTitle".'此错误出现在cmd.ExecuteNonQuery()旁边,请有人帮我解决这个问题吗?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.Data.SqlClient;

namespace RegistrationForm5
{
    public partial class Registration : System.Web.UI.Page
    {
        SqlCommand cmd = new SqlCommand();
        SqlConnection con = new SqlConnection();
        protected void Page_Load(object sender, EventArgs e)
        {
            con.ConnectionString = (@"Data Source=DESKTOP-20J5J59;Initial Catalog=RegistrationWebForm1;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
            con.Open();
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            SqlCommand cmd = new SqlCommand("insert into reg" + "(Title, Name, ID, Email, Mobile, Major, Note)values(@TxtTitle, @TxtName, @TxtID, @TxtEmail, @TxtMobile, @LstMajor, @TxtNote)", con);


            cmd.Parameters.AddWithValue("@Title", TxtTitle.Text);
            cmd.Parameters.AddWithValue("@Name", TxtName.Text);
            cmd.Parameters.AddWithValue("@ID", TxtID.Text);
            cmd.Parameters.AddWithValue("@Email", TxtEmail.Text);
            cmd.Parameters.AddWithValue("@Mobile", TxtMobile.Text);
            cmd.Parameters.AddWithValue("@Major", LstMajor.SelectedItem.ToString());
            cmd.Parameters.AddWithValue("@Note", TxtNote.Text);
            cmd.ExecuteNonQuery();
            Label1.Text = "Your request has been submitted successfully";

            con.Close();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

这里的问题是cmd变量,您在参数@Title中添加了一个正确的参数,即@TxtTitle,我看到其他参数都不正确,最终代码可能是这样的:

protected void Button1_Click(object sender, EventArgs e)
{
    SqlCommand cmd = new SqlCommand("insert into reg" + "(Title, Name, ID, Email, Mobile, Major, Note)values(@TxtTitle, @TxtName, @TxtID, @TxtEmail, @TxtMobile, @LstMajor, @TxtNote)", con);

    cmd.Parameters.AddWithValue("@TxtTitle", TxtTitle.Text);
    cmd.Parameters.AddWithValue("@TxtName", TxtName.Text);
    cmd.Parameters.AddWithValue("@TxtID", TxtID.Text);
    cmd.Parameters.AddWithValue("@TxtEmail", TxtEmail.Text);
    cmd.Parameters.AddWithValue("@TxtMobile", TxtMobile.Text);
    cmd.Parameters.AddWithValue("@LstMajor", LstMajor.SelectedItem.ToString());
    cmd.Parameters.AddWithValue("@TxtNote", TxtNote.Text);
    cmd.ExecuteNonQuery();
    Label1.Text = "Your request has been submitted successfully";

    con.Close();
}