如何在数据库中插入数组文本框?我必须在访问中保存每个新框,它应该在不同的行中。保存数据时,它有一个错误对象引用未设置为对象的实例
Public Class Form1 Dim boxes As New List(Of TextBox)
将组合调暗为新列表(组合框)
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
在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