对象引用未设置为对象的实例插入数据库sql数组

时间:2016-02-26 02:04:35

标签: vb.net ms-access

如何在数据库中插入数组文本框?我必须在访问中保存每个新框,它应该在不同的行中。在保存数据时,它没有设置为对象实例的错误对象引用

Public Class Form1
    Dim boxes As New List(Of TextBox) 
     

Dim combo As New List(Of ComboBox)

    Private Sub Addbuttons(buttonCount As Integer)
        Dim newbox As TextBox   Dim newcombo As ComboBox

        For i As Integer = 1 To buttonCount
            newbox = New TextBox
            newbox.Size = New Drawing.Size(575, 35)
            newbox.Location = New Drawing.Point(10, 10 + 35 * (i - 1))
            newbox.Name = "TextBox" & i
            newbox.Text = newbox.Name
            'connect it to a handler, save a reference to the array and add it to the form controls
            boxes.Add(newbox)
            Me.Controls.Add(newbox)
        Next  For i As Integer = 1 To buttonCount
        newcombo = New ComboBox
        newcombo.Size = New Drawing.Size(57, 20)
        newcombo.Location = New Drawing.Point(864, 531 + 70 * (i - 1))
        combo.Add(newcombo)
        Me.Controls.Add(newcombo)
    Next
    End Sub
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Addbuttons(Val(TextBox1.Text))
    End Sub
    Private Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
        addbuyer()
    End Sub
   Private Sub addbuyer()
    Dim newbox As TextBox
      Try
        datab = " Insert INTO sample (sample1,sample2) values ( '" & newbox.Text & "','" & newqty.Text & "')"
        connDB()
        cmd = New OleDbCommand(datab, conn)
        Dim i As Integer
        i = cmd.ExecuteNonQuery
        If i > 0 Then
            '  MsgBox("Added SUccesfully", MsgBoxStyle.Information, "Confirmation")


        Else
            MsgBox("Failed Adding", MsgBoxStyle.Information, "Alert!")
        End If
    Catch ex As Exception
        MsgBox(ex.Message)
    Finally
        cmd.Dispose()
        conn.Close()

    End Try
End Sub

End Class

1 个答案:

答案 0 :(得分:0)

addbuyer中,Dim newbox As TextBox不算什么,而且是导致错误的原因。

您已将所有文本框控件添加到boxes,因此您需要在插入数据库时​​循环。一种方法是通过引用循环并传递每个文本框:

Private Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
  For Each t As TextBox In boxes
      addbuyer(t)
  Next
End Sub

Private Sub addbuyer(ByRef newbox As TextBox)       
    Try
        datab = " Insert INTO sample (sample1) values ( '" & newbox.Text & "')"
        connDB()
        cmd = New OleDbCommand(datab, conn)
        Dim i As Integer
        i = cmd.ExecuteNonQuery
        If i > 0 Then
            MsgBox("Added SUccesfully", MsgBoxStyle.Information, "Confirmation")


        Else
            MsgBox("Failed Adding", MsgBoxStyle.Information, "Alert!")
        End If
    Catch ex As Exception
        MsgBox(ex.Message)
    Finally
        cmd.Dispose()
        conn.Close()

    End Try
End Sub