我正在VB.Net中创建一个程序,它连接到数据库并允许用户添加,编辑和删除记录等。但是我希望能够使用模块创建子例程和函数并引用它们我的表格。我找到了一种方法来获取数据集中表的字段名称,以便我可以使用循环来获取字段并将数据写入其中。但问题是,用于写入这些字段的控件必须明确命名(例如txtFirst_Name或cboSubjects)。这使我很难完成我的任务,因为我不能使用循环来添加到字段,我将不得不为表单上的每个输入字段写一行,而不是例如循环10次。以下是我的代码的副本,包括使用潜艇。
添加到数据库
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
query = "Select * from Supplier"
getTable()
Try
Dim cb As New OleDbCommandBuilder(da)
Dim dSet_NewRow As DataRow
dSet_NewRow = dSet.Tables("Table").NewRow
dSet_NewRow.Item("Name") = TextBox1.Text
dSet_NewRow.Item("Address1") = TextBox2.Text
dSet_NewRow.Item("Address2") = TextBox3.Text
dSet_NewRow.Item("Town") = TextBox4.Text
dSet_NewRow.Item("County") = TextBox5.Text
dSet_NewRow.Item("Country") = TextBox6.Text
dSet_NewRow.Item("PostCode") = TextBox7.Text
dSet.Tables("Table").Rows.Add(dSet_NewRow)
da.Update(dSet, "Table")
dSet.Tables.Clear()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
连接数据库
Sub Connect()
Try
conn.ConnectionString = connString
conn.Open()
'If conn.State = ConnectionState.Open Then
'MsgBox("open")
'End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
将信息放入数据集
Sub getTable()
Try
da = New OleDbDataAdapter(query, conn)
da.Fill(dSet, "Table")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
有没有人知道如何使用循环动态分配输入,而不必命名textbox1,textbox2 ......
答案 0 :(得分:0)
您的重用方法会提供变量。
Public Shared Sub LoadSomeData(name As String, addr1 As String, addr2 As String, town As String, county As String, country As String, pc As String)
Try
Dim cb As New OleDbCommandBuilder(da)
Dim dSet_NewRow As DataRow
dSet_NewRow = dSet.Tables("Table").NewRow
dSet_NewRow.Item("Name") = name
dSet_NewRow.Item("Address1") = addr1
dSet_NewRow.Item("Address2") = addr2
dSet_NewRow.Item("Town") = town
dSet_NewRow.Item("County") = county
dSet_NewRow.Item("Country") = country
dSet_NewRow.Item("PostCode") = pc
dSet.Tables("Table").Rows.Add(dSet_NewRow)
da.Update(dSet, "Table")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
用法:
LoadSomeData(textbox1.Text, textbox2.Text, textbox3.Text, textbox4.Text, textbox5.Text, textbox6.Text, textbox7.Text)
虽然我希望您能够使用具有某些含义的名称来命名文本框 - tbName,tbAddress等...