无法将null插入数据库vb.net

时间:2016-01-27 14:39:43

标签: database vb.net null

我一直在尝试将null插入数据库,但每次我都失败了。我尝试了几个代码,但没有任何工作。当我尝试这段代码时:

   If String.IsNullOrEmpty(TextBox2.Text) Then
        TextBox2.Text = DBNull.Value
    Else
        TextBox2.Text = TextBox2.Text

    End If

它给了我一个错误:

Value of type 'System.DBNull' cannot be converted to 'String'.

当我尝试这个时:

    If Not String.IsNullOrEmpty(TextBox2.Text) = True Then
        TextBox2 = System.DBNull.Value
    Else
        TextBox2.Text = TextBox2.Text
    End If

它给了我一个错误:

  Value of type 'System.DBNull' cannot be converted to 'System.Windows.Forms.TextBox'.

在这些代码之前,我添加了一些验证,以使用户必须填写文本框。

这是我收到此错误的地方:

    dsNewRow.Item("emp_name") = TextBox1.Text
    dsNewRow.Item("emp_age") = TextBox2.Text  'This is the place where I am getting this error'
    dsNewRow.Item("emp_gend") = ComboBox1.Text
    dsNewRow.Item("emp_dob") = DateTimePicker1.Text
    dsNewRow.Item("emp_mstatus") = TextBox4.Text
    dsNewRow.Item("emp_qual") = RichTextBox1.Text
    dsNewRow.Item("emp_exp") = RichTextBox2.Text

它还显示:

 Input string was not in a correct format.Couldn't store <> in emp_age Column.  Expected type is Int32.

2 个答案:

答案 0 :(得分:1)

可以使用这样的语法将DbNull.Value分配给DataRow列 (当然,假设emp_age列可以为空)

dsNewRow.Item("emp_age") = 
    If(string.IsNullOrWhiteSpace(TextBox2.Text), DbNull.Value, TextBox2.Text)

在这里,您使用If conditional operator将列的值设置为DbNull.Value或TextBox2.Text

但是,还有另一个问题无法立即显现。此emp_age列需要一个整数值,您不应该在其中写入字符串。最好检查输入值以确保您具有有效的整数值

Dim age As Integer
If Int32.TryParse(TextBox2.Text, age) Then
    dsNewRow.Item("emp_age") = age
Else
    dsNewRow.Item("emp_age") = DBNull.Value
End If

答案 1 :(得分:0)

无论您尝试什么,TextBox2.Text永远不会是DbNull.Value。所以你必须找到一种方法来定义空值。如果允许将空字符串视为DbNull,则可以写:

dsNewRow.Item("emp_age") = If(String.IsNullOrEmpty(TextBox2.Text), DbNull.Value, TextBox2.Text)

但是,这仍然需要列emp_age支持DbNull值。

相关问题