Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 错误:System.Data.SqlClient.SqlException(0x80131904):将数据类型nvarchar转换为数字时出错_C#_Asp.net_Registration - Fatal编程技术网

C# 错误:System.Data.SqlClient.SqlException(0x80131904):将数据类型nvarchar转换为数字时出错

C# 错误:System.Data.SqlClient.SqlException(0x80131904):将数据类型nvarchar转换为数字时出错,c#,asp.net,registration,C#,Asp.net,Registration,我试图创建一个注册页面,但是遇到了一个额外的错误! 我试图实现的是将用户输入的代码传输到数据库中。 但是,由于单击submit按钮后遇到错误,我无法实现我想要的目标。 任何帮助都将不胜感激 Error Message: Error:System.Data.SqlClient.SqlException (0x80131904): Error converting data type nvarchar to numeric. at System.Data.SqlClient.SqlConne

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

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)
);
注册页面的My 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);

    }

} 
使用系统;
使用系统配置;
使用系统数据;
使用System.Linq;
使用System.Web;
使用System.Web.Security;
使用System.Web.UI;
使用System.Web.UI.HTMLControl;
使用System.Web.UI.WebControl;
使用System.Web.UI.WebControl.WebParts;
使用System.Xml.Linq;
使用System.Data.SqlClient;
公共部分类注册:System.Web.UI.Page
{
静态只读字符串scriptErrorUsername=
“\n”+
“警报(\“错误-用户名已被使用!请输入另一个用户名\”);\n”+
"";
静态只读字符串scriptSuccessNewAccount=
“\n”+
“警报(\“您的帐户已成功创建-谢谢!\”);\n”+
"";
受保护的无效页面加载(对象发送方、事件参数e)
{
如果(iPostBack)
{
SqlConnection conn=new SqlConnection(@“数据源=(LocalDB)\v11.0;AttachDbFilename=D:\Desktop\TemporarySter\App_Data\legitdatabase.mdf;集成安全性=True;连接超时=30;MultipleActiveResultSets=True”);
conn.Open();
string checkuser=“从客户机中选择count(*),其中cUserName=”+userTB.Text+”;
SqlCommand com=新的SqlCommand(检查用户,conn);
int temp=Convert.ToInt32(com.ExecuteScalar().ToString());
如果(温度==1)
{
回答。写(“用户名已被占用!请选择其他用户名。”);
}
康涅狄格州关闭();
}
}
受保护的无效提交按钮单击(对象发送者,事件参数e)
{
尝试
{
SqlConnection conn=new SqlConnection(@“数据源=(LocalDB)\v11.0;AttachDbFilename=D:\Desktop\TemporarySter\App_Data\legitdatabase.mdf;集成安全性=True;连接超时=30;MultipleActiveResultSets=True”);
conn.Open();
类型csType=this.GetType();
SqlCommand-com;
SqlDataReader-rdr;
string strSQLSelect=“按客户名称从客户订单中选择客户名称”;
com=新的SqlCommand(strSQLSelect,conn);
rdr=com.ExecuteReader();
while(rdr.Read()==true)
{
if(userTB.Text==(字符串)rdr[“cUsername”])
{
RegisterStartupScript(csType,“Error”,scriptErrorUsername);
康涅狄格州关闭();
rdr.Close();
回来
}
}
string insertQuery=“插入客户端(cFirstName、clatname、[cD.O.B]、cCompanyName、cAddress、cCity、cZipCode、cPhoneNo、cFax、cEmail、cUsername、cPassword)值(@firstname、@lastname、@dob、@companyname、@address、@city、@zipcode、@phoneno、@fax、@email、@username、@password)”;
com=新的SqlCommand(insertQuery,conn);
com.Parameters.AddWithValue(“@firstname”,firstnameTB.Text);
com.Parameters.AddWithValue(“@lastname”,lastnameTB.Text);
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”,postalcodeb.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();
重定向(“ClientLogin.aspx”);
回答。写下(“恭喜!您的注册成功!”);
RegisterStartupScript(csType,“Success”,scriptSuccessNewAccount);
康涅狄格州关闭();
}
捕获(例外情况除外)
{
Write(“错误:+ex.ToString());
}
}
受保护的无效重置按钮\u单击(对象发送方,事件参数e)
{
重定向(“~/Registration.aspx”,true);
}
} 

您将电话号码声明为数字字段,因此需要将文本转换为整数

 [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));

电话号码值是cs中的字符串:

com.Parameters.AddWithValue("@phoneno", contactnumberTB.Text.ToString());
在您的表格中,它是数字:

[cPhoneNo] NUMERIC (18)   NOT NULL,
[编辑:]
您应该更新表中的数据类型

在代码中进行以下更改

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,

嗨,先生,我又发现一个错误。错误:System.OverflowException:值对于Int16太大或太小。在System.Convert.ToInt16(字符串值)注册时,在System.Int16.Parse(字符串s、NumberStyles样式、NumberFormatInfo信息)中,在submitButton\u单击(对象发送方、事件参数e)在d:\Desktop\TemporarySter\Registration.aspx.cs中:行74@SarahCollins您放入TextBoxI的
cPhoneNo
的值是多少?我设置了一个限制,只允许8个数字。例子:88888888@SarahCollins我更新了。您需要使用
Convert.ToInt32
,因为当您的答案在技术上正确时,请参考此选项