当我插入空文本框时发生类型转换错误 [英] Type Conversion Error when i insert empty textbox

查看:92
本文介绍了当我插入空文本框时发生类型转换错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

SQL查询

 创建 表格产品(产品 nvarchar (max),
价格数字( 18  2 ),
折扣数字( 18  2 )默认  0 )



 创建 >过程 sp1

 @ p1   NVARCHAR (MAX),

 @ p2   NUMERIC ( 18  2 ),

 @ p3   NUMERIC ( 18  2 )默认  0 
 AS 
开始
插入  INTO 产品>值( @ p1  @ p2  @ p3 )
结束
 GO  



编码

 com = 新建 SqlCommand(" ,
        com.CommandType = CommandType.StoredProcedure
        尝试
            com.Parameters.AddWithValue(" ,TextBox1.Text)
            com.Parameters.AddWithValue(" ,TextBox2.Text)
            com.Parameters.AddWithValue(" ,TextBox3.Text)
            com.ExecuteNonQuery()
            MsgBox(" )

        捕获,例如 As 异常
            MsgBox(例如消息)
        结束 尝试 



当我插入空的textbox3时,它显示类型转换错误.
预先感谢
普里扬(S.Priyan)


[edit]添加了代码块[/edit]

解决方案

只需执行以下操作;

...
    com.Parameters.AddWithValue("@p2", (TextBox2.Text.Trim().Length == 0 ? "0" : TextBox2.Text))
    com.Parameters.AddWithValue("@p3", (TextBox3.Text.Trim().Length == 0 ? "0" : TextBox3.Text))
...


您使用数字,int等数据类型,然后要保存空文本,然后输入错误sqlserver.因此,如果您需要保存空文本,则可以将文本值更改为0(或默认值),然后保存.因此,只要该字段为空,就插入零...


Hi All,

Sql Query

create table products(product nvarchar(max),
price numeric(18,2),
discount numeric(18,2) default 0)



CREATE PROCEDURE sp1

@p1 NVARCHAR(MAX),

@p2 NUMERIC(18,2),

@p3 NUMERIC(18,2) default 0
AS
BEGIN
INSERT INTO products  VALUES (@p1 ,@p2 ,@p3 )
End
GO



coding

com = New SqlCommand("sp1", con)
        com.CommandType = CommandType.StoredProcedure
        Try
            com.Parameters.AddWithValue("@p1", TextBox1.Text)
            com.Parameters.AddWithValue("@p2", TextBox2.Text)
            com.Parameters.AddWithValue("@p3", TextBox3.Text)
            com.ExecuteNonQuery()
            MsgBox("Record Added....")

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try



it shows Type Conversion Error when i insert empty textbox3.....

Advance Thanks
S.Priyan


[edit]added code block[/edit]

解决方案

Just do the following;

...
    com.Parameters.AddWithValue("@p2", (TextBox2.Text.Trim().Length == 0 ? "0" : TextBox2.Text))
    com.Parameters.AddWithValue("@p3", (TextBox3.Text.Trim().Length == 0 ? "0" : TextBox3.Text))
...


You use the numeric, int etc datatype then you want to save empty text then give error sqlserver. so if you require the empty text save then you change the text value is 0(or default value) then save.


u are trying to insert an empty value into a numeric field so it fails so insert a zero whenever the field is empty...


这篇关于当我插入空文本框时发生类型转换错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆