首页 > 解决方案 > 将自动生成的文本框中的数据插入 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 个自动生成的文本框

如何将文本框中的这些数据保存到数据库中?

标签: sqlsql-servervb.nettextbox

解决方案


由于 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

推荐阅读