none
How to save the content of dynamically created text boxes on FlowLayoutPanel into database RRS feed

  • Question

  • Hi, 

    Please guide me How to save the content of dynamically created text boxes on FlowLayoutPanel into database. This is my very first question and related to my work project.

    The text box is created with content(Integer value) every time user presses the button. The number of text box can be 1-20 or anything. I try to use the code below but i am not sure this is the correct approach. And also I cannot manage to loop through all the text box on FlowLayoutPanel. Thank you so much.

      Dim list As New List(Of Integer)
            Dim value As Integer
            Dim counter As Integer = noOfTextbox
            For Each tb In flowPanel.Controls
                If TypeOf tb Is TextBox Then
                    txtNo = DirectCast(tb, TextBox)
                    list.Add(txtNo.Text)
                End If
            Next

    Sunday, August 11, 2019 4:56 PM

Answers

  • Hello,

    • What type of database e.g. SQL-Server, MS-Access etc.
    • Do you want to subscribe to any events for the TextBoxes
    • What information will be stored in the TextBox controls

    I'll get you started with collecting TextBox controls into a List(Of TextBox).

    Add the following code module to your project.

    Public Module Extensions
        ''' <summary>
        ''' Provides access to all controls on a form including
        ''' controls within containers e.g. panel and group-box etc.
        ''' </summary>
        ''' <typeparam name="T"></typeparam>
        ''' <param name="control"></param>
        ''' <returns></returns>
        <Runtime.CompilerServices.Extension>
        Public Iterator Function Descendants(Of T As Class)(control As Control) As IEnumerable(Of T)
            For Each child As Control In control.Controls
    
                Dim currentChild = TryCast(child, T)
                If currentChild IsNot Nothing Then
                    Yield currentChild
                End If
    
                If child.HasChildren Then
                    For Each descendant As T In child.Descendants(Of T)()
                        Yield descendant
                    Next
                End If
            Next
        End Function
    End Module
    

    To get the TextBoxes and show name and values

    Public Class Form1
        Private TextBoxList As New List(Of TextBox)
    
        Private Sub GetTextBoxesFromFlowControlButton_Click(sender As Object, e As EventArgs) _
            Handles GetTextBoxesFromFlowControlButton.Click
    
            TextBoxList = FlowLayoutPanel1.Descendants(Of TextBox).ToList()
    
            For Each textBox As TextBox In TextBoxList
                Console.WriteLine($"Name: {textBox.Name} Value: {textBox.Text}")
            Next
    
        End Sub
    End Class
    

    See if there are any TextBoxes that have no value

    TextBoxList = FlowLayoutPanel1.Descendants(Of TextBox).ToList()
    Dim anyEmpty = TextBoxList.Any(Function(tb) String.IsNullOrWhiteSpace(tb.Text))

    Perform a conversion

    TextBoxList = FlowLayoutPanel1.Descendants(Of TextBox).ToList()
    Dim anyEmpty = TextBoxList.Any(Function(tb) String.IsNullOrWhiteSpace(tb.Text))
    If Not anyEmpty Then
        Dim value As Integer = 0
        For Each TextBox As TextBox In TextBoxList
            If Integer.TryParse(TextBox.Text, value) Then
                Console.WriteLine($"Name: {TextBox.Name} Value: {value}")
            Else
                Console.WriteLine($"Name: {TextBox.Name} not a valid integer")
            End If
        Next
    End If
    Going back to saving, it's depending on the bullet points above.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    • Marked as answer by DoruBogyi Sunday, August 25, 2019 8:11 AM
    Sunday, August 11, 2019 11:49 PM
    Moderator
  • Hi

    Here is one way to do it. This is a complete example.

    ' Form1 with FlowLayoutPanel1,
    ' Buttons 1, 2 and 3
    Option Strict On
    Option Explicit On
    Public Class Form1
      ' set up a path for saving TextBox contents
      Dim FilePath As String = IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.Desktop, "SaveTB.txt")
      Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ' add some TextBoxes to FlowLayoutPanel1
        ' for testing
        For i As Integer = 1 To 10
          Dim ntb As New TextBox
          With ntb
            .Text = i.ToString
            .Width = 100
          End With
          FlowLayoutPanel1.Controls.Add(ntb)
        Next
      End Sub
      Sub ReadTB()
        ' clear the FlowLayoutPanel and load
        ' data from file and create a new 
        ' TextBox for each
        Dim lst As List(Of String) = IO.File.ReadAllLines(FilePath).ToList
        If lst.Count > 0 Then
          FlowLayoutPanel1.Controls.Clear()
          For Each s As String In lst
            Dim ntb As New TextBox
            With ntb
              .Text = s
              .Width = 100
            End With
            FlowLayoutPanel1.Controls.Add(ntb)
          Next
        End If
      End Sub
      Sub SaveTB()
        ' Save the current set of TextBox
        ' contents to file.
        Using sw As New IO.StreamWriter(FilePath, False)
          For Each c As Control In FlowLayoutPanel1.Controls
            If c.GetType() Is GetType(TextBox) Then
              sw.WriteLine(c.Text)
            End If
          Next
        End Using
      End Sub
      Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ' save the current TextBox contents
        ' NOTE: if there are no current TB then
        ' an emptyfile will be made.
        SaveTB()
      End Sub
      Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        ' load the file contents. NOTE: if the 
        ' old data was not saved then the file
        ' is likely an empty file so no TB will
        ' be created.
        ReadTB()
      End Sub
      Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        ' just for testing to show that the
        ' FlowLayoutPanel was truly empty
        ' before refilling from the file.
        FlowLayoutPanel1.Controls.Clear()
      End Sub
    End Class


    Regards Les, Livingston, Scotland


    • Edited by leshay Monday, August 12, 2019 12:09 AM
    • Marked as answer by DoruBogyi Sunday, August 25, 2019 8:11 AM
    Monday, August 12, 2019 12:07 AM
  • Hi,

    If you resolve the issue, please mark the helpful as answer. It will be beneficial to other community.

    Best Regards,

    Alex


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by DoruBogyi Sunday, August 25, 2019 8:11 AM
    Tuesday, August 13, 2019 2:02 AM

All replies

  • Hello,

    • What type of database e.g. SQL-Server, MS-Access etc.
    • Do you want to subscribe to any events for the TextBoxes
    • What information will be stored in the TextBox controls

    I'll get you started with collecting TextBox controls into a List(Of TextBox).

    Add the following code module to your project.

    Public Module Extensions
        ''' <summary>
        ''' Provides access to all controls on a form including
        ''' controls within containers e.g. panel and group-box etc.
        ''' </summary>
        ''' <typeparam name="T"></typeparam>
        ''' <param name="control"></param>
        ''' <returns></returns>
        <Runtime.CompilerServices.Extension>
        Public Iterator Function Descendants(Of T As Class)(control As Control) As IEnumerable(Of T)
            For Each child As Control In control.Controls
    
                Dim currentChild = TryCast(child, T)
                If currentChild IsNot Nothing Then
                    Yield currentChild
                End If
    
                If child.HasChildren Then
                    For Each descendant As T In child.Descendants(Of T)()
                        Yield descendant
                    Next
                End If
            Next
        End Function
    End Module
    

    To get the TextBoxes and show name and values

    Public Class Form1
        Private TextBoxList As New List(Of TextBox)
    
        Private Sub GetTextBoxesFromFlowControlButton_Click(sender As Object, e As EventArgs) _
            Handles GetTextBoxesFromFlowControlButton.Click
    
            TextBoxList = FlowLayoutPanel1.Descendants(Of TextBox).ToList()
    
            For Each textBox As TextBox In TextBoxList
                Console.WriteLine($"Name: {textBox.Name} Value: {textBox.Text}")
            Next
    
        End Sub
    End Class
    

    See if there are any TextBoxes that have no value

    TextBoxList = FlowLayoutPanel1.Descendants(Of TextBox).ToList()
    Dim anyEmpty = TextBoxList.Any(Function(tb) String.IsNullOrWhiteSpace(tb.Text))

    Perform a conversion

    TextBoxList = FlowLayoutPanel1.Descendants(Of TextBox).ToList()
    Dim anyEmpty = TextBoxList.Any(Function(tb) String.IsNullOrWhiteSpace(tb.Text))
    If Not anyEmpty Then
        Dim value As Integer = 0
        For Each TextBox As TextBox In TextBoxList
            If Integer.TryParse(TextBox.Text, value) Then
                Console.WriteLine($"Name: {TextBox.Name} Value: {value}")
            Else
                Console.WriteLine($"Name: {TextBox.Name} not a valid integer")
            End If
        Next
    End If
    Going back to saving, it's depending on the bullet points above.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    • Marked as answer by DoruBogyi Sunday, August 25, 2019 8:11 AM
    Sunday, August 11, 2019 11:49 PM
    Moderator
  • Hi

    Here is one way to do it. This is a complete example.

    ' Form1 with FlowLayoutPanel1,
    ' Buttons 1, 2 and 3
    Option Strict On
    Option Explicit On
    Public Class Form1
      ' set up a path for saving TextBox contents
      Dim FilePath As String = IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.Desktop, "SaveTB.txt")
      Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ' add some TextBoxes to FlowLayoutPanel1
        ' for testing
        For i As Integer = 1 To 10
          Dim ntb As New TextBox
          With ntb
            .Text = i.ToString
            .Width = 100
          End With
          FlowLayoutPanel1.Controls.Add(ntb)
        Next
      End Sub
      Sub ReadTB()
        ' clear the FlowLayoutPanel and load
        ' data from file and create a new 
        ' TextBox for each
        Dim lst As List(Of String) = IO.File.ReadAllLines(FilePath).ToList
        If lst.Count > 0 Then
          FlowLayoutPanel1.Controls.Clear()
          For Each s As String In lst
            Dim ntb As New TextBox
            With ntb
              .Text = s
              .Width = 100
            End With
            FlowLayoutPanel1.Controls.Add(ntb)
          Next
        End If
      End Sub
      Sub SaveTB()
        ' Save the current set of TextBox
        ' contents to file.
        Using sw As New IO.StreamWriter(FilePath, False)
          For Each c As Control In FlowLayoutPanel1.Controls
            If c.GetType() Is GetType(TextBox) Then
              sw.WriteLine(c.Text)
            End If
          Next
        End Using
      End Sub
      Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ' save the current TextBox contents
        ' NOTE: if there are no current TB then
        ' an emptyfile will be made.
        SaveTB()
      End Sub
      Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        ' load the file contents. NOTE: if the 
        ' old data was not saved then the file
        ' is likely an empty file so no TB will
        ' be created.
        ReadTB()
      End Sub
      Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        ' just for testing to show that the
        ' FlowLayoutPanel was truly empty
        ' before refilling from the file.
        FlowLayoutPanel1.Controls.Clear()
      End Sub
    End Class


    Regards Les, Livingston, Scotland


    • Edited by leshay Monday, August 12, 2019 12:09 AM
    • Marked as answer by DoruBogyi Sunday, August 25, 2019 8:11 AM
    Monday, August 12, 2019 12:07 AM
  • Thank you so much, it is working well . 
    Monday, August 12, 2019 3:26 PM
  • Thank you so much for answer. I now learn another way of saving data. 
    Monday, August 12, 2019 3:28 PM
  • Hi,

    If you resolve the issue, please mark the helpful as answer. It will be beneficial to other community.

    Best Regards,

    Alex


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by DoruBogyi Sunday, August 25, 2019 8:11 AM
    Tuesday, August 13, 2019 2:02 AM