简体   繁体   English

将数据类型nvarchar从C#转换为sql时出错

[英]Error Converting datatype nvarchar to int from c# to sql

Hi Guys please help me out in my code where I got stuck and went wrong, I have two tables; 大家好,请在我的代码中遇到麻烦的地方帮我,我有两个表; one employee table and another branch table. 一个雇员表和另一个分支表。 The branch id will be stored in employee table which is a foreign key. 分支机构ID将存储在外表雇员表中。 When I'm inserting the data through stored procedure where I kept the code like bleow 当我通过存储过程插入数据时,我像bleow这样保存代码

Create procedure [dbo].[Insertemployee]

@d28 int,@d1 nchar(15),@d2 nchar(30),@d3 int,@d4 nchar(10),@d5 nchar(20),@d6 nchar(30),@d7 varchar(100),@d8 nchar(100),@d9 nchar(10),@d10 nchar(10),@d11 nchar(30),@d12 nchar(30),@d13 nchar(30),@d14 nchar(30),@d15 nchar(30),@d16 date,@d17 varchar(100),@d18 int,@d19 int,@d20 int,@d21 int,@d22 int,@d23 int,@d24 int,@d25 image,@d26 date,@d27 date,@d29 nchar(10)
AS
    BEGIN
        SET NOCOUNT ON
    BEGIN TRY
        BEGIN TRANSACTION
insert into Employee(Id,StaffID,StaffName,Branchid,Gender,DOB,FatherName,PermanentAddress,Country,PhoneNo,MobileNo,DateOfJoining,VisaNumber,PassportNumber,PassportExpiryDate,NationalityID,NationalityIDExpiryDate,Designation,BasicSalary,CostOfAllowance,HRA,TeaAndSnacks,Bonus,Loan,OtherDeduction,Picture,createddate,lastmodified,Active) VALUES (@d28,@d1,@d2,(select branchid from Branch where Branch.BranchName=@d3),@d4,@d5,@d6,@d7,@d8,@d9,@d10,@d11,@d12,@d13,@d14,@d15,@d16,@d17,@d18,@d19,@d20,@d21,@d22,@d23,@d24,@d25,@d26,@d27,@d29);
COMMIT TRANSACTION
    END TRY
        BEGIN CATCH
            IF @@TRANCOUNT >0
            BEGIN
                ROLLBACK TRANSACTION
            END
            EXECUTE uspLogError 
        END CATCH
END;`

and my front end code is below 我的前端代码在下面

 cmd = new SqlCommand("InsertEmployee");
            cmd.CommandType = CommandType.StoredProcedure;
                cmd.Connection = con;
            cmd.Parameters.AddWithValue("@d28",txtID.Text);

                cmd.Parameters.AddWithValue("@d26", System.DateTime.Now);
                cmd.Parameters.AddWithValue("@d27", System.DateTime.Now);

            cmd.Parameters.AddWithValue("@d1", txtStaffID.Text);

                cmd.Parameters.AddWithValue("@d2",txtStaffName.Text);
                cmd.Parameters.AddWithValue("@d3",txtDepartment.Text);
                cmd.Parameters.AddWithValue("@d4",cmbGender.Text);
                cmd.Parameters.AddWithValue("@d6",txtFatherName.Text);
                cmd.Parameters.AddWithValue("@d7",txtPAddress.Text);
                cmd.Parameters.AddWithValue("@d8",txtTAddress.Text);
                cmd.Parameters.AddWithValue("@d9",txtPhoneNo.Text);
                cmd.Parameters.AddWithValue("@d10",txtMobileNo.Text);
                cmd.Parameters.AddWithValue("@d11",dtpDateOfJoining.Value);
                cmd.Parameters.AddWithValue("@d12",visanumber.Text.Trim());
                cmd.Parameters.AddWithValue("@d14",PassportExpirydate.Text);
                cmd.Parameters.AddWithValue("@d15",NationalityID.Text.Trim());
            if (NationalityID.Text == "")
            {
                cmd.Parameters.AddWithValue("@d16", "");
            }
            else
            {
                cmd.Parameters.AddWithValue("@d16", NationalityExpirydate.Value);
            }
                cmd.Parameters.AddWithValue("@d17",txtDesignation.Text.Trim());
                cmd.Parameters.AddWithValue("@d13",Passportnumber.Text.Trim());
                cmd.Parameters.AddWithValue("@d18",Convert.ToInt32(txtBasicSalary.Text.Trim()));
                if (txtLIC.Text == "")
                {
                    cmd.Parameters.AddWithValue("@d19", 0);
                }
                else
                {
                    cmd.Parameters.AddWithValue("@d19",Convert.ToInt32(txtLIC.Text.Trim()));

                }
                if (txtGrpInsurance.Text == "")
                {
                    cmd.Parameters.AddWithValue("@d21", 0);
                }
                else
                {
                    cmd.Parameters.AddWithValue("@d21",Convert.ToInt32(txtGrpInsurance.Text.Trim()));
                }
                if (txtFamilyBenefitFund.Text == "")
                {
                    cmd.Parameters.AddWithValue("@d22",0);
                }
                else
                {
                    cmd.Parameters.AddWithValue("@d22",Convert.ToInt32(txtFamilyBenefitFund.Text.Trim()));
                }
                if (txtLoans.Text == "")
                {
                    cmd.Parameters.AddWithValue("@d23",0);
                }
                else
                {
                    cmd.Parameters.AddWithValue("@d23",Convert.ToInt32(txtLoans.Text.Trim()));
                }
                if (txtOtherDeductions.Text == "")
                {
                    cmd.Parameters.AddWithValue("@d24",0);
                }
                else
                {
                    cmd.Parameters.AddWithValue("@d24",Convert.ToInt32(txtOtherDeductions.Text.Trim()));
                }
                if (txtIncomeTax.Text == "")
                {
                    cmd.Parameters.AddWithValue("@d20",0);
                }
                else
                {
                    cmd.Parameters.AddWithValue("@d20",Convert.ToInt32(txtIncomeTax.Text.Trim()));
                }
            cmd.Parameters.AddWithValue("@d29", chkActive.Text);
                cmd.Parameters.AddWithValue("@d5",DOB.Text);
                MemoryStream ms = new MemoryStream();
                Bitmap bmpImage = new Bitmap(pictureBox1.Image);

                bmpImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

                byte[] data = ms.GetBuffer();
                SqlParameter p = new SqlParameter("@d25", SqlDbType.Image);
                p.Value = data;
                cmd.Parameters.Add(p);
                cmd.ExecuteNonQuery();

d3 field can accept int but you are passing string` d3字段可以接受int,但您正在传递字符串`

default type of TextBox is string TextBox默认类型是字符串

you can fix this by converting to int 您可以通过转换为int来解决此问题

cmd.Parameters.AddWithValue("@d3",txtDepartment.Text);

to

 cmd.Parameters.AddWithValue("@d3",Convert.ToInt(txtDepartment.Text));

You are passing few fields as string to DB datatype int : 您正在将几个字段作为字符串传递给DB数据类型int:

cmd.Parameters.AddWithValue("@d28",txtID.Text); cmd.Parameters.AddWithValue(“ @ d28”,txtID.Text);

cmd.Parameters.AddWithValue("@d3",txtDepartment.Text); cmd.Parameters.AddWithValue(“ @ d3”,txtDepartment.Text);

you should convert them to int prior passing it to db 您应该先将它们转换为int,然后再传递给db

 cmd.Parameters.AddWithValue("@d28",Convert.ToInt32(txtID.Text.Trim()));
  cmd.Parameters.AddWithValue("@d3",Convert.ToInt32(txtDepartment.Text.Trim()));

Just curious how come your txtDepartment be type of int , either you have to make a check whether there is string being passed or its an number . 只是好奇您的txtDepartment如何成为int类型,您必须检查是否传递了字符串或它的数字。 If it accepts only number you might have to check the value being passed to txtDepartment.Text and vice -versa. 如果它仅接受数字,则可能必须检查传递给txtDepartment.Text的值,反之亦然。

I think the above answer is correct and he find the issues as well(Congrats). 我认为以上答案是正确的,他也发现了问题(恭喜)。 But the actual problem here is the Parameters.AddWithValue . 但是这里的实际问题是Parameters.AddWithValue It will not allows you to specify the type and will cause this kind of datatype conversion errors. 它不允许您指定类型,并且会导致这种数据类型转换错误。 So What i suggest you is, use Parameters.Add() instead for Parameters.AddWithValue() So that you can specify the type of expecting data and there by able to validate the input. 因此,我建议您使用Parameters.Add()代替Parameters.AddWithValue() ,以便可以指定期望数据的类型,并在那里可以验证输入。 you can see the below example(which help you to solve the issue as well): 您可以看到以下示例(也可以帮助您解决问题):

cmd.Parameters.Add("@d28", SqlDbType.Int).Value = int.Parse(txtID.Text.Trim());

Where SqlDbType is an Enumeration which Specifies SQL Server-specific data type of a field, property, for use in a SqlParameter. 其中SqlDbType是一个枚举,它指定要在SqlParameter中使用的字段的特定于SQL Server的数据类型,属性。 int.TryParse() will be another best suggestion for you to perform error free conversion from string to integer. int.TryParse()将是您执行从字符串到整数的无错误转换的另一个最佳建议。

Update : It seems The SP accepts values of different types, but you are giving all as string(.Text). 更新:似乎SP接受不同类型的值,但是您都将其作为字符串(.Text)给出。 This will create the same issue, So changing only "@d28" will not solve the issue, Try to read the attached link and make necessary changes in the code. 这将产生相同的问题,因此仅更改"@d28"将无法解决问题,请尝试阅读附件的链接并在代码中进行必要的更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM