如何将datagridview中的所有记录显示保存到数据库中

时间:2016-01-15 12:35:31

标签: sql database vb.net ms-access datagridview

我有这个代码只保存datagridview的顶行, 有人可以帮我修改这段代码,以便它保存datagridview中的所有行。即时通讯使用vb 2010,我的数据库是ms访问。提前谢谢你。

{ [Error: ENOENT: no such file or directory, open '/avatar/myFile.png']
  errno: -2,
  code: 'ENOENT',
  syscall: 'open',
  path: '/avatar/myFile.png' }

1 个答案:

答案 0 :(得分:2)

根据显示的内容和注入的最佳实践,您应该使用数据源(如DataTable)进行工作,例如如果向用户显示DataGridView时没有行然后创建一个新的DataTable,将DataTable设置为DataGridView的DataSource然后当您准备在DataGridView中保存这些行时,将DataGridView的DataSource强制转换为DataTable并使用逻辑类似于以下

Dim dt As DataTable = CType(DataGridView1.DataSource, DataTable)
If dt.Rows.Count > 0 Then
    Using cn As New OleDb.OleDbConnection With {.ConnectionString = "Your connection string"}
        ' part field list done here
        Using cmd As New OleDb.OleDbCommand With
            {
                .Connection = cn,
                .CommandText = "Insert into tblreportlog(EmpID,empname,department) values (@EmpID,@empname,@department)"
            }

            ' TODO - field names, field types
            cmd.Parameters.AddRange(
                {
                    {New OleDb.OleDbParameter With {.ParameterName = "@EmpID", .DbType = DbType.Int32}},
                    {New OleDb.OleDbParameter With {.ParameterName = "@empname", .DbType = DbType.Int32}},
                    {New OleDb.OleDbParameter With {.ParameterName = "@department", .DbType = DbType.String}}
                }
            )

            Dim Affected As Integer = 0

            cn.Open()

            Try
                For Each row As DataRow In dt.Rows
                    ' this should not be a auto-incrementing key
                    cmd.Parameters("@EmpID").Value = row.Field(Of Integer)("FieldName goes here")
                    cmd.Parameters("@empname").Value = row.Field(Of Integer)("FieldName goes here")
                    cmd.Parameters("@department").Value = row.Field(Of String)("FieldName goes here")

                    Affected = cmd.ExecuteNonQuery
                    If Affected <> 1 Then
                        Console.WriteLine("Error message, insert failed")
                    End If
                Next
            Catch ex As Exception
                '
                ' handle exception
                '
                ' for now
                MessageBox.Show("Failed with: " & ex.Message)
                ' decide to continue or not
            End Try
        End Using
    End Using
End If

另一方面,如果有新行包含当前行,我们会按上述方式转换数据源,然后根据需要检查新行和验证。

For Each row As DataRow In dt.Rows
    If row.RowState = DataRowState.Added Then
        If Not String.IsNullOrWhiteSpace(row.Field(Of String)("CompanyName")) Then

其他选项,通过ide中的数据向导使用DataAdapter或设置数据,其中BindingNavigator使用保存按钮进行设置。

如果获取新主键很重要,那么所有方法的方法也可以这样做。

以下代码示例来自this MSDN code sample,其中显示了如何使用OleDb连接和命令获取新密钥。

Public Function AddNewRow(ByVal CompanyName As String, ByVal ContactName As String, ByVal ContactTitle As String, ByRef Identfier As Integer) As Boolean 
    Dim Success As Boolean = True 


Try 
    Using cn As New OleDb.OleDbConnection(Builder.ConnectionString) 
        Using cmd As New OleDb.OleDbCommand("", cn) 

            cmd.CommandText = "INSERT INTO Customer (CompanyName,ContactName,ContactTitle) Values (@CompanyName,@ContactName,@ContactTitle)" 

            cmd.Parameters.AddWithValue("@CompanyName", CompanyName.Trim) 
            cmd.Parameters.AddWithValue("@ContactName", ContactName.Trim) 
            cmd.Parameters.AddWithValue("@ContactTitle", ContactTitle.Trim) 

            cn.Open() 

            cmd.ExecuteNonQuery() 

            cmd.CommandText = "Select @@Identity" 
            Identfier = CInt(cmd.ExecuteScalar) 

        End Using 
    End Using 

Catch ex As Exception 
    Success = False 
End Try 

Return Success 


End Function