System.Data.SqlClient.SqlException: 'Must declare the scalar variable "@TxtTitle".'

System.Data.SqlClient.SqlException: 'Must declare the scalar variable "@TxtTitle".'

单击提交按钮后,出现此错误: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();
        }
    }
}

这里的问题是 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();
}