I want to have a label in a form whose text value changes depending upon the value of an instance of a class. It looks like I can bind the text value of the label to an object dataSource. When I try this it does not seem to work.
Me.Label4.DataBindings.Add(New System.Windows.Forms.Binding("Text", Me.ItemInfoBindingSource, "ItemNumber", True, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged))
My itemInfoBindingSource:
Me.ItemInfoBindingSource.DataSource = GetType(CFP.ItemInfo)
and the class definition:
Public Class ItemInfo
Public Property ItemNumber As String = "rename"
Public Property Description As String
Public Property FileLocation As String
Public Property CompileHistory As List(Of CompileHistory)
End Class
I think what I have done is to bind to a class, not an instance of a class. Thinking about it, what I really want to do is bind an instance of a class to a label... How? Is this possible?
Yes, this is possible, but you need to raise an event to let the label know that the property has changed. If you were using a type like a BindingList, this would be done automatically, but you're trying to bind to a String
which doesn't raise PropertyChanged events.
To add the event to your class:
Here's the result of these changes for just the ItemNumber property in your class:
Public Class ItemInfo
Implements System.ComponentModel.INotifyPropertyChanged
Private _itemNumber As String = "rename"
Public Property ItemNumber As String
Get
Return _itemNumber
End Get
Set(value As String)
_itemNumber = value
RaiseEvent PropertyChanged(Me,
New System.ComponentModel.PropertyChangedEventArgs("ItemNumber"))
End Set
End Property
Public Event PropertyChanged(sender As Object,
e As System.ComponentModel.PropertyChangedEventArgs) _
Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
End Class
I added a text box and label to a form, added the data binding in the Form.Load
event, added a field called ItemInfoBindingSource of type ItemInfo, and updated the ItemNumber in the TextBox.TextChanged
event.
Private ItemInfoBindingSource As New ItemInfo
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Label1.DataBindings.Add("Text", Me.ItemInfoBindingSource, "ItemNumber")
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) _
Handles TextBox1.TextChanged
ItemInfoBindingSource.ItemNumber = TextBox1.Text
End Sub
Now, when you type in the text box, ItemNumber.Set is called, and raises an event to let anything listening know that it's been changed. The label is listening, and it updates its Text property so that you can see the new value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With