将数据从gridview获取到访问数据库

时间:2015-08-02 00:39:21

标签: asp.net vb.net gridview

我主要使用它,但是我无法将所有gridview数据导入到数据库中,这里的第一行数据只是代码:

Try
    Dim pid As String
    Dim pname As String
    Dim Connection As OleDbConnection
    Connection = New OleDbConnection()
    Dim connolaString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("App_Data/my_products.mdb;") + ";Persist Security Info=True"
    Connection.ConnectionString = connolaString
    Dim commander As OleDbCommand = New OleDbCommand()
    commander.Connection = Connection
    commander.CommandText = "INSERT INTO prdtemp ( pid, pname ) VALUES ( @pid, @pname )"
    Connection.Open()
    For x As Integer = 0 To GridView1.Rows.Count - 1
        pid = GridView1.Rows(x).Cells(1).Text
        pname = GridView1.Rows(x).Cells(2).Text
        commander.Parameters.AddWithValue("@pid", pid)
        commander.Parameters.AddWithValue("@pname", pname)
        commander.ExecuteNonQuery()
        commander.Dispose()
    Next
    Connection.Close()
Catch ex As Exception
    lblMessage.Text = (ex.Message)
End Try

由于某种原因(ex.message)说连接属性没有初始化,尽管我说它只获得了gridview的第一行。请帮忙。

1 个答案:

答案 0 :(得分:0)

您似乎在循环中调用commander.Dispose()方法。这将释放所有对象的资源,并在第二次循环迭代中破坏。

编辑:我建议你用OleDbCommand语句包装Using,当你退出Using块时,它会处理对象处理。

请参阅此处的示例: https://msdn.microsoft.com/en-us/library/7shabkb8%28v=vs.110%29.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1

我没有测试下面的修改后的代码,但它应该可以解决您的问题。

Try
    Dim pid As String
    Dim pname As String
    Dim Connection As OleDbConnection
    Connection = New OleDbConnection()
    Dim connolaString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("App_Data/my_products.mdb;") + ";Persist Security Info=True"
    Using commander As New OleDbCommand(connolaString)
        commander.Connection = Connection
        commander.CommandText = "INSERT INTO prdtemp ( pid, pname ) VALUES ( @pid, @pname )"
        Connection.Open()
        For x As Integer = 0 To GridView1.Rows.Count - 1
            pid = GridView1.Rows(x).Cells(1).Text
            pname = GridView1.Rows(x).Cells(2).Text
            commander.Parameters.Clear()
            commander.Parameters.AddWithValue("@pid", pid)
            commander.Parameters.AddWithValue("@pname", pname)
            commander.ExecuteNonQuery()
        Next
        Connection.Close()
    End Using
Catch ex As Exception
    lblMessage.Text = (ex.Message)
End Try