Error:System.Data.SqlClient.SqlException (0x80131904): Error converting data type nvarchar to numeric

Error:System.Data.SqlClient.SqlException (0x80131904): Error converting data type nvarchar to numeric

我正在尝试创建一个注册页面,但是遇到了一个额外的错误! 我想要实现的是将用户输入的代码传输到数据库中。 但是,由于单击提交按钮后遇到错误,我无法实现我想要的 objective 。 任何帮助将不胜感激!

Error Message:
Error:System.Data.SqlClient.SqlException (0x80131904): Error converting data type nvarchar to     numeric. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at Registration.submitButton_Click(Object sender, EventArgs e) in d:\Desktop\TemporarySter\Registration.aspx.cs:line 80 ClientConnectionId:c3fd51e0-9dc7-49ba-ab88-313267504802

我的SQL数据库代码

  CREATE TABLE [dbo].[Client] (
    [ClientNo]     INT            IDENTITY (1, 1) NOT NULL,
    [cFirstName]   NCHAR (10)     NOT NULL,
    [cLastName]    NCHAR (50)     NOT NULL,
    [cD.O.B]       DATE           NOT NULL,
    [cCompanyName] NVARCHAR (255) NOT NULL,
    [cAddress]     NVARCHAR (255) NOT NULL,
    [cCity]        NVARCHAR (255) NOT NULL,
    [cZipCode]     NCHAR (10)     NOT NULL,
    [cPhoneNo] NUMERIC (18)   NOT NULL,
    [cFax]         NUMERIC (18)   NOT NULL,
    [cEmail]       NVARCHAR (MAX) NOT NULL,
    [cUsername]    NVARCHAR (50)  NOT NULL,
    [cPassword]    NVARCHAR (50)  NOT NULL,
    CONSTRAINT [PK_Client] PRIMARY KEY CLUSTERED ([ClientNo] ASC)
);

我的 aspx.cs 注册页面代码

  using System;
    using System.Configuration;
    using System.Data;
    using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class Registration : System.Web.UI.Page
{
    static readonly string scriptErrorUsername =
        "<script language =\"javascript\">\n" +
        "alert (\"Error - Username is already taken! Please key in another Username\");\n" +
        "</script>";
    static readonly string scriptSuccessNewAccount =
        "<script language=\"javascript\">\n" +
        "alert (\"Your account has been successfully created - Thank You!\");\n" +
        "</script>";
    protected void Page_Load(object sender, EventArgs e)
    {

        if (IsPostBack)
        {
            SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\Desktop\TemporarySter\App_Data\legitdatabase.mdf;Integrated Security=True;Connect Timeout=30;MultipleActiveResultSets=true");
            conn.Open();
            string checkuser = "select count(*) from Client where cUserName= '" + userTB.Text + "'";
            SqlCommand com = new SqlCommand(checkuser, conn);
            int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
            if (temp == 1)
            {
                Response.Write("Username is already taken! Please choose another username.");
            }
            conn.Close();
        }
    }
    protected void submitButton_Click(object sender, EventArgs e)
    {
        try
        {
            SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\Desktop\TemporarySter\App_Data\legitdatabase.mdf;Integrated Security=True;Connect Timeout=30;MultipleActiveResultSets=true");
            conn.Open();
            Type csType = this.GetType();
            SqlCommand com;
            SqlDataReader rdr;
            string strSQLSelect = "SELECT cUsername FROM Client ORDER BY cUsername";         
            com = new SqlCommand(strSQLSelect, conn);
            rdr = com.ExecuteReader();

            while (rdr.Read() == true)
            {
                if (userTB.Text == (string)rdr["cUsername"])
                {
                    ClientScript.RegisterStartupScript(csType, "Error", scriptErrorUsername);
                    conn.Close();
                    rdr.Close();
                    return;
                }
            }


            string insertQuery = "insert into Client (cFirstName, cLastName, [cD.O.B], cCompanyName, cAddress, cCity, cZipCode, cPhoneNo, cFax, cEmail, cUsername, cPassword) values (@firstname,@lastname,@dob,@companyname,@address,@city,@zipcode,@phoneno,@fax,@email,@username,@password)";
            com = new SqlCommand(insertQuery, conn);
            com.Parameters.AddWithValue("@firstname", firstnameTB.Text);
            com.Parameters.AddWithValue("@lastname", lastnameTB.Text);
            com.Parameters.AddWithValue("@dob", dateTB.Text.ToString());
            com.Parameters.AddWithValue("@companyname", companyTB.Text);
            com.Parameters.AddWithValue("@address", addressTB.Text);
            com.Parameters.AddWithValue("@city", cityTB.Text);
            com.Parameters.AddWithValue("@zipcode", postalcodeTB.Text);
            com.Parameters.AddWithValue("@phoneno", contactnumberTB.Text.ToString());
            com.Parameters.AddWithValue("@fax", faxTB.Text.ToString());
            com.Parameters.AddWithValue("@email", emailTB.Text);
            com.Parameters.AddWithValue("@username", userTB.Text);
            com.Parameters.AddWithValue("@password", passTB.Text);

            com.ExecuteNonQuery();
            Response.Redirect("ClientLogin.aspx");
            Response.Write("Congratulations! Your registration is successful!");
            ClientScript.RegisterStartupScript(csType, "Success", scriptSuccessNewAccount);
            conn.Close();


        }
        catch (Exception ex)
        {
            Response.Write("Error:" + ex.ToString());
        }


}
    protected void resetButton_Click(object sender, EventArgs e)
    {


        Response.Redirect("~/Registration.aspx", true);

    }

} 

您将 Phone 声明为数字字段,因此您需要将文本转换为整数

 [cPhoneNo] NUMERIC (18)   NOT NULL
 [cFax]     NUMERIC (18)   NOT NULL

这样使用:

com.Parameters.AddWithValue("@phoneno", Convert.ToInt32(contactnumberTB.Text));
com.Parameters.AddWithValue("@fax", Convert.ToInt32(faxTB.Text));

STOP USING ADD WITH VALUES

phone数值是你cs中的一个字符串:

com.Parameters.AddWithValue("@phoneno", contactnumberTB.Text.ToString());

在你的table中它是数字:

[cPhoneNo] NUMERIC (18)   NOT NULL,

[编辑:] 您应该更新 table 中的数据类型。

对您的代码进行以下更改

com.Parameters.AddWithValue("@phoneno", Convert.ToDouble(contactnumberTB.Text.ToString()));
com.Parameters.AddWithValue("@@fax", Convert.ToDouble(faxTB..Text.ToString()));

您需要进行更改,因为您试图在数字字段中插入字符串值。 通过定义它,您在 db 中声明以下字段是数字,因此应用程序将失败并返回字符串值。这就是为什么需要进行上述更改才能使数值翻倍的原因。

[cPhoneNo] NUMERIC (18)   NOT NULL,
[cFax]         NUMERIC (18)   NOT NULL,