sql - 将自动生成的文本框中的数据插入 SQL Server 数据库
问题描述
我创建了一个代码,用于使用按钮单击和函数在 vb.net 中生成文本框
Public Function AddNewTextBox() As System.Windows.Forms.TextBox
Dim txt As New System.Windows.Forms.TextBox()
Me.Controls.Add(txt)
txt.Top = cLeft * 30
txt.Left = 100
'txt.Text = "TextBox " & Me.cLeft.ToString
cLeft = cLeft + 1
txt.ForeColor = Color.DarkGreen
txt.BackColor = Color.Gray
txt.Font = New Font("Arial", 14.0, FontStyle.Regular)
txt.Size = New Size(237, 31)
txt.Location = New Point(156, 130 + top1)
Return txt
End Function
在按钮
Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'call the function
AddNewTextBox()
End Sub
我试过这个
cmd.CommandText = "INSERT INTO userlog ([username],[userlastname]) Values ( @username) "
cmd.Parameters.AddWithValue("@username", txt.Text(i).Text)
cmd.Parameters.AddWithValue("@userlastname", txt.Text(i).Text)
但出现错误
txt.Text(i)
因为 txt 仅在 AddNewTextBox 函数中声明。
我制作了 3 个自动生成的文本框
如何将文本框中的这些数据保存到数据库中?
解决方案
由于 TextBox 正在被添加到 Form 的控件集合中,因此您可以使用OfType可枚举方法来获取所有 TextBox 控件。更重要的是,我可能会将生成的 TextBox 的Tag分配给所需的字段名称,以便您可以在控件集合中查询 TextBox 的第一个实例,其标签等于所需的字段。
另外值得一提的是,您可以使用 With 关键字来删除一些不必要的代码。
综上所述,您的 AddNewTextBox 方法将如下所示:
Public Function AddNewTextBox(ByVal fieldName As String) As System.Windows.Forms.TextBox
Dim txt As New System.Windows.Forms.TextBox()
Me.Controls.Add(txt)
With
.Top = cLeft * 30
.Left = 100
'.Text = "TextBox " & Me.cLeft.ToString
cLeft = cLeft + 1
.ForeColor = Color.DarkGreen
.BackColor = Color.Gray
.Font = New Font("Arial", 14.0, FontStyle.Regular)
.Size = New Size(237, 31)
.Location = New Point(156, 130 + top1)
.Tag = fieldName
End With
Return txt
End Function
您的 Button 的点击事件如下所示:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'call the function
Dim txt As TextBox = AddNewTextBox("username")
End Sub
您的参数化查询将如下所示:
Dim usernameTextBox As TextBox = Me.Controls.OfType(Of TextBox).FirstOrDefault(Function(txt) txt.Tag IsNot Nothing AndAlso txt.Tag = "username")
If usernameTextBox IsNot Nothing Then
cmd.Parameters.AddWithValue("@username", usernameTextBox.Text)
End If
推荐阅读
- jenkins - 如何在单个 Jenkins 作业中添加多个 Jenkins 作业作为构建参数
- javascript - 角度路由器未加载正确的组件
- javascript - 使用 Express.js 发布到 SQL Server api
- mysql - 使用工作台将数据库导入 MySQL 需要很长时间
- pom.xml - 从不同的 url(存储库)添加“过时”的 maven 依赖项
- sql - 在where子句中查询日期和具体时间3
- terraform - Terraform - 从同一脚本填充变量值
- angularjs - AngularJS 库网址
- r - 如何按整秒对 xts 时间序列进行分组/求和
- ios - 使用 ionic 生成 iOS 构建时出现错误,即“沙箱与 Podfile.lock 不同步”。在 MAC 莫哈韦