我正在处理由datagridview
组成的客户数据库和vb.net表单。
我包括3列:
customer_id, customer_name, customer_Notes
我创建了两个功能来简化我的工作,一个功能用于将数据从datagridview
插入到MS Access数据库中,另一个功能用于更新datagridview中显示的数据。
嗯,我遇到了问题。我收到有关从'DBNull'类型到'string'类型转换的错误消息。
无论我是插入还是更新以下列之一,如果都无法填充datagridview列中的至少一列,则会出现错误消息:
customer_id, customer_name, customer_Notes
否则一切都很好。
在我在这里提出问题之前,我已经在网上搜索过,并且我知道我将首先测试DBNull,但是我没有学会正确的方法。
插入功能:
Public Sub insert_customer(ByVal customer_id As Integer, ByVal customer_name As String, ByVal customer_address As String, ByVal customer_phone As String, ByVal customer_notes As String)
Try
Dim cmd As New OleDbCommand("insert into tblCustomers (CustomerID , CustomerName , CustomerNotes) values (@CustomerID,@CustomerName , @CustomerNotes) ", conn_Access)
cmd.Parameters.Add("@CustomerID", OleDbType.Integer).Value = customer_id
cmd.Parameters.Add("@CustomerName", OleDbType.VarWChar).Value = customer_name
cmd.Parameters.Add("@CustomerNotes", OleDbType.VarChar).Value = customer_notes
conn_Access.Open()
cmd.ExecuteNonQuery()
conn_Access.Close()
cmd = Nothing
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
更新功能:
Public Sub update_customer(ByVal customer_name As String, ByVal customer_notes As String, ByVal Customer_ID2 As Integer)
Try
Dim cmd As New OleDbCommand("update tblCustomers set CustomerName= @CustomerName , CustomerNotes= @CustomerNotes where CustomerID = @CustomerID2 ", conn_Access)
cmd.Parameters.Add("@CustomerName", OleDbType.VarChar).Value = customer_name
cmd.Parameters.Add("@CustomerNotes", OleDbType.VarChar).Value = customer_notes
cmd.Parameters.Add("@CustomerID2", OleDbType.Integer).Value = Customer_ID2
conn_Access.Open()
cmd.ExecuteNonQuery()
conn_Access.Close()
cmd = Nothing
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
私有子Btn_save_Click(ByVal发送者作为System.Object,ByVal e作为System.EventArgs)处理Btn_save.Click '更新 'اولعمود 试试
For i As Integer = 0 To DataGridView1.Rows.Count - 2
With DataGridView1.Rows(i)
'اول عمود
If count_customer_id_from_customers(.Cells(0).Value) = 1 Then
'update
update_customer(.Cells(1).Value, .Cells(2).Value, .Cells(3).Value, .Cells(4).Value, .Cells(0).Value)
Else
'insert
insert_customer(.Cells(0).Value, .Cells(1).Value, .Cells(2).Value, .Cells(3).Value, .Cells(4).Value)
End If
End With
Next
load_Customers()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
任何帮助将不胜感激
预先感谢