Insert data from auto generated textbox to SQL Server database

点点圈 提交于 2019-12-13 02:52:32

问题


I have created a code for generating a text box in vb.net using button click and function

 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

In the button

Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'call the function
        AddNewTextBox()

End Sub

I have tried this

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)

but getting an error in

txt.Text(i)

since txt is declared only in AddNewTextBox function.

I have made 3 auto generated text boxs

How do I save this data inside the text box to the database?


回答1:


Add a FlowlayoutPanel to your form and set the FlowDirection to TopDown. (as commented by @jmcilhinney) This saves calculating the position of the text boxes.

It doesn't make sense to have a function returning a text box when you never use the return value.

The data access code uses the .Add method suggested by @SMor. See http://www.dbdelta.com/addwithvalue-is-evil/ and https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/ and another one: https://dba.stackexchange.com/questions/195937/addwithvalue-performance-and-plan-cache-implications

I had to guess at the datatypes. Check your database for correct types.

The values come from the controls collection of the FlowLayoutPanel where the controls were added.

Using blocks ensure that you database objects are closed and disposed even if there is an error. Pass the connection string directly to the constructor of the connection and the command text and connection directly to the constructor of the command.

Public Sub AddNewTextBox()
    Dim txt As New System.Windows.Forms.TextBox()
    txt.Name = "user" & nameTextBox.ToString
    txt.ForeColor = Color.DarkGreen
    txt.BackColor = Color.Gray
    txt.Font = New Font("Arial", 14.0, FontStyle.Regular)
    txt.Size = New Size(120, 30)
    FlowLayoutPanel1.Controls.Add(txt)
End Sub

Private Sub UpdateUsers()
    Using cn As New SqlConnection("Your connection string")
        Using cmd As New SqlCommand("INSERT INTO userlog ([username],[userlastname]) Values ( @username, @userlastname);", cn)
            cmd.Parameters.Add("@username", SqlDbType.VarChar).Value = FlowLayoutPanel1.Controls(0).Text
            cmd.Parameters.AddWithValue("@userlastname", SqlDbType.VarChar).Value = FlowLayoutPanel1.Controls(1).Text
            cn.Open()
            cmd.ExecuteNonQuery()
        End Using
    End Using
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    AddNewTextBox()
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    UpdateUsers()
End Sub

EDIT

    For Each tb As TextBox In FlowLayoutPanel1.Controls
        If tb.Text = "" Then
            MessageBox.Show("Please fill all text boxes before Updating")
            Return
        End If
    Next



回答2:


Since the TextBox is being added to the control collection of the Form, you can use the OfType enumerable method to get all TextBox controls. What's more I would probably assign the Tag of the generated TextBox to the desired field name so that you can query the control collection for the first instance of the TextBox who's tag equals the desired field.

Also its worth mentioning that you can use the With keyword to get rid of some unnecessary code.

With all that being said, your AddNewTextBox method would look like this:

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

Your Button's click event would look like this:

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

And your parameterized query would look like this:

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


来源:https://stackoverflow.com/questions/56970533/insert-data-from-auto-generated-textbox-to-sql-server-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!