locked
Making changes to data and save it. RRS feed

  • Question

  • I need to save changes made in DataBound Labels via a TextBox.  By clicking on a Label the text apears in the TextBox where changes can be made to it, this changes need to be save back to the database.  

    Some of the code I use is shown below.  

     Dim recipeSelected As String = TitleListBox.SelectedItem.ToString()
                        Dim result = recipesLst.Where(Function(x) x.RecipeName = recipeSelected).FirstOrDefault()
                        'Form1.TextBox1.Text = result.ID.ToString()
    
                        'Recipe Name Label
                        Dim TitleFontStyle As FontStyle = FontStyle.Bold + FontStyle.Italic
                        Dim TitleFont As New System.Drawing.Font("Comic Sans MS", 14, TitleFontStyle)
                        Dim RecipeNameLabel As New Label()
                        With RecipeNameLabel
                            .AutoSize = True
                            .MaximumSize = New Size(370, 100)
                            .MinimumSize = New Size(370, 10)
                            .TextAlign = ContentAlignment.MiddleCenter
                            .Text = result.RecipeName
                            If TestModeCheckBox.Checked = True Then
                                .BackColor = Color.Gold
                            Else
                                .BackColor = Color.Transparent
                            End If
                            .Font = TitleFont
                            .Location = New Point(75, 50)
                        End With
                        Controls.Add(RecipeNameLabel)
                        RecipeNameLabel.Parent = Form1
                        X = RecipeNameLabel.Left
                        Y = RecipeNameLabel.Bottom + 10
                        AddHandler RecipeNameLabel.Click, AddressOf ContentLabel_Click
    
                        'Comment Label
                        Dim CommentLabel As New Label()
                        With CommentLabel
                            .AutoSize = True
                            .MaximumSize = New Size(200, 150)
                            .MinimumSize = New Size(150, 10)
                            .TextAlign = ContentAlignment.MiddleLeft
                            .Text = result.Comment
                            If TestModeCheckBox.Checked = True Then
                                .BackColor = Color.Gold
                            Else
                                .BackColor = Color.Transparent
                            End If
                            .Font = New System.Drawing.Font("Comic Sans MS", 8)
                            .Location = New Point(X, Y)
                        End With
                        Controls.Add(CommentLabel)
                        CommentLabel.Parent = Form1
                        X = CommentLabel.Left
                        Y = CommentLabel.Bottom
                        AddHandler CommentLabel.Click, AddressOf ContentLabel_Click
    
                        'Quantity Label
                        Dim QuantityLabel As New Label()
                        With QuantityLabel
                            .AutoSize = True
                            .MaximumSize = New Size(360 - CommentLabel.Width, 150)
                            .MinimumSize = New Size(360 - CommentLabel.Width, 10)
                            .TextAlign = ContentAlignment.BottomRight
                            .Text = result.Quantity
                            If TestModeCheckBox.Checked = True Then
                                .BackColor = Color.Gold
                            Else
                                .BackColor = Color.Transparent
                            End If
                            .Font = New System.Drawing.Font("Comic Sans MS", 8)
                            .Location = New Point(445 - QuantityLabel.Width, CommentLabel.Bottom - QuantityLabel.Height)
                        End With
                        Controls.Add(QuantityLabel)
                        QuantityLabel.Parent = Form1
                        AddHandler QuantityLabel.Click, AddressOf ContentLabel_Click
    
    
    
     Private Sub ContentLabel_Click(sender As Object, e As EventArgs)
            currentLabel = DirectCast(sender, Label)
            InputTextBox.Text = currentLabel.Text
        End Sub



    Thursday, February 20, 2020 4:57 PM

All replies

  • Hi

    So, what is your question?


    Regards Les, Livingston, Scotland

    Thursday, February 20, 2020 5:17 PM
  • How do I save the changes made to the database.  
    Thursday, February 20, 2020 5:20 PM
  • You are missing data binding which should be done with a BindingSource. Having your data in the ListBox.DataSource set to a BindingSource where the BindingSource DataSource would be set to your recipes and then the desired controls be it labels and/or TextBoxes are bound the data can now be changes via INotificationChanged Interface which is transparent to you when working with DataTable -> BindingSource while this is not true when say working with classes which need to be setup e.g.

    Imports System.ComponentModel
    Imports System.Runtime.CompilerServices
    Imports CommonPractice.Interfaces
    
    Namespace CommonPractice.BaseNotifyClasses
    	Public Class Person
    		Implements INotifyPropertyChanged, IPerson
    
    		Private _firstName As String
    		Private _lastName As String
    		Public Property Id() As Integer
    
    		Public Property FirstName() As String
    			Function(get) _firstName
    			Set(ByVal value As String)
    				_firstName = value
    				OnPropertyChanged()
    			End Set
    		End Property
    
    		Public Property LastName() As String
    			Function(get) _lastName
    			Set(ByVal value As String)
    				_lastName = value
    				OnPropertyChanged()
    			End Set
    		End Property
    
    
    
    		public event PropertyChangedEventHandler PropertyChangedEvent
    OnPropertyChanged([CallerMemberName] string propertyName = null)
    		protected virtual void OnPropertyChanged((CallerMemberName) String propertyName = Nothing)
    			PropertyChangedEvent?.Invoke(Me, New PropertyChangedEventArgs(propertyName))
    	End Class
    End Namespace


    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

    Thursday, February 20, 2020 5:45 PM
  • I got no clue what to do with this Karen, I'm sure there must be an simpler way of doing this.  
    Thursday, February 20, 2020 6:09 PM
  • I got no clue what to do with this Karen, I'm sure there must be an simpler way of doing this.  

    Many developers don't understand this. Here is a simple example I just used to reply to another question so I only present this to show INotifiyPropertyChanged for performing data binding on a strong typed list.

    The task is to add the selected item from ListBox1 to ListBox2 and when doing so my code never even references ListBox2 in button click event. You would need something similar if working with a list. Is there an easier way? The better question is there a harder way? YES.

    Imports System.ComponentModel
    Imports System.Runtime.CompilerServices
    
    Public Class Person
        Implements INotifyPropertyChanged
        Private _firstName1 As String
        Private _lastName1 As String
    
        Public Property FirstName() As String
            Get
                Return _firstName1
            End Get
            Set
                _firstName1 = Value
                OnPropertyChanged()
            End Set
        End Property
    
        Public Property LastName() As String
            Get
                Return _lastName1
            End Get
            Set
                _lastName1 = Value
                OnPropertyChanged()
            End Set
        End Property
    
        Public Overrides Function ToString() As String
            Return $"{FirstName} {LastName}"
        End Function
    
        Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
    
        Protected Overridable Sub OnPropertyChanged(<CallerMemberName> Optional ByVal propertyName As String = Nothing)
            PropertyChangedEvent?.Invoke(Me, New PropertyChangedEventArgs(propertyName))
        End Sub
    End Class

    .

    Imports System.ComponentModel
    
    Public Class Form1
        Private _bindingListForListBox1 As New BindingList(Of Person)()
        Private ReadOnly _bindingListForListBox2 As New BindingList(Of Person)()
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    
            If ListBox1.SelectedIndex > -1 Then
                _bindingListForListBox2.Add(CType(ListBox1.SelectedItem, Person))
            End If
    
        End Sub
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Dim people As New List(Of Person) From {
                    New Person() With {.FirstName = "Karen", .LastName = "Payne"},
                    New Person() With {.FirstName = "Anne", .LastName = "Jones"},
                    New Person() With {.FirstName = "Bob", .LastName = "Smith"}}
    
            _bindingListForListBox1 = New BindingList(Of Person)(people)
    
            ListBox1.DataSource = people
            ListBox2.DataSource = _bindingListForListBox2
    
        End Sub
    End Class


    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

    Thursday, February 20, 2020 6:20 PM
  • Karen. No this is not for me.  I am 49 years old, the one thing I regret is not starting coding since childhood. I just want to do this one app as a gift to my wife. 

    Ther must be some thing I can understand.  Using the wizard aning data conections I kind off understud aswell as the coding vor saving etc. But the wizard does not work properly on my pc for some reson.

    Thursday, February 20, 2020 7:13 PM
  • If this is your very first project without database knowledge and then compared it to what would be done with a decent understanding of databases this is what you might come up with as a model.

    Note that ingredients are broken out from a recipe which means you don't have to be concerned with empty fields or not enough fields for a recipe. That is just the start.

    And as stated before there should only be one database and on a regular basis have a full backup done. 


    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

    Thursday, February 20, 2020 7:49 PM
  • Karen please you making this to complicated.  I have started this meny years ago and then abandoned it deu to my illnes for about 4 years now. I was using the wizard then for most of the databinding work.  

    Please just help me with code that will work with the code I have working now.  

    Thursday, February 20, 2020 8:03 PM
  • Hi VB Novice Hendri,

    In order to save the changes to database, you can use update UPDATE statement.

    Here's the code you can refer to:

    Public Class Form1
        Private lst As List(Of Label) = New List(Of Label)()
        Private result As Recipe = New Recipe() With {
            .ID = 1,
            .RecipeName = "n1",
            .Comment = "c1",
            .Quantity = "q1"
        }
        Private currentLabel As Label
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Dim RecipeNameLabel As Label = New Label() With {
                .Text = result.RecipeName,
                .AutoSize = True,
                .MaximumSize = New Size(300, 150),
                .MinimumSize = New Size(300, 10),
                .Font = New Font("Comic Sans MS", 10),
                .Location = New Point(75, 50),
                .Tag = "RecipeNameLabel"
            }
            Controls.Add(RecipeNameLabel)
            lst.Add(RecipeNameLabel)
            AddHandler RecipeNameLabel.Click, AddressOf ContentLabel_Click
            Dim CommentLabel As Label = New Label() With {
                .Text = result.Comment,
                .AutoSize = True,
                .MaximumSize = New Size(300, 150),
                .MinimumSize = New Size(300, 10),
                .Font = New Font("Comic Sans MS", 10),
                .Location = New Point(75, 70),
                .Tag = "CommentLabel"
            }
            Controls.Add(CommentLabel)
            lst.Add(CommentLabel)
            AddHandler CommentLabel.Click, AddressOf ContentLabel_Click
            Dim QuantityLabel As Label = New Label() With {
                .Text = result.Quantity,
                .AutoSize = True,
                .MaximumSize = New Size(300, 150),
                .MinimumSize = New Size(300, 10),
                .Font = New Font("Comic Sans MS", 10),
                .Location = New Point(75, 90),
                .Tag = "QuantityLabel"
            }
            Controls.Add(QuantityLabel)
            lst.Add(QuantityLabel)
            AddHandler QuantityLabel.Click, AddressOf ContentLabel_Click
        End Sub
        Private Sub ContentLabel_Click(ByVal sender As Object, ByVal e As EventArgs)
            currentLabel = CType(sender, Label)
            InputTextBox.Text = currentLabel.Text
        End Sub
        Private Sub Save_Click(sender As Object, e As EventArgs) Handles Save.Click
            For Each lb In lst
    
                If lb.Tag = currentLabel.Tag Then
                    lb.Text = InputTextBox.Text
                End If
            Next
    
            currentLabel.Text = InputTextBox.Text
            Dim connString As String = "Connection"
    
            Using conn As SqlConnection = New SqlConnection(connString)
                conn.Open()
                Dim cmdText As String = $"UPDATE RecipeTable SET RecipeName = '{lst(0).Text}', Comment = '{lst(1).Text}' , Quantity = '{lst(2).Text}' WHERE ID = {result.ID}"
    
                Using cmd As SqlCommand = New SqlCommand With {
                    .Connection = conn
                }
                    cmd.CommandText = cmdText
                    cmd.ExecuteNonQuery()
                End Using
            End Using
        End Sub
    End Class
    Class Recipe
        Public Property ID As Integer
        Public Property RecipeName As String
        Public Property Comment As String
        Public Property Quantity As String
    End Class

    Data in my database:

    When click the button, data will be updated based on values of Labels.

    Result:

    Hope it can help you.

    Best Regards,

    Xingyu Zhao


    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.

    Friday, February 21, 2020 8:48 AM