binding list(of class) to datagridview in vb.net - vb.net

I have a class that contains a list of data that gets populated from a datastream. I want to bind that list to a datagridview so it automatically populates as the list does. However the list isn't refreshing as the data comes in. I have something like this.
Public class MyClass
Private mData as list(Of networkData)
Public Property Data() as list(Of networkData)
Get
return mData
End Get
Set
mData = value
End Set
End Property
' some other properties that aren't imporant
' stuff to load Data with data from network stream
end class
Public class networkDat
Private rawdata as string
Public Property rawdata() as string
Get
return mrawdata
End Get
Set
mrawData = value
End Set
End Property
' some other properties that aren't imporant
' functions to parse rawdata into the other properties
End Class
'form
Public Class dataviewer
Dim dataView as datagridViewer = new datagridviewer()
Private Sub dataviewer_load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
dim x as myClass = new myClass() 'new will start the datastream
datagridview.datasource = x.Data
End Sub
Since I started the datastream first dataviewer will have an inital set of data. However it doesn't update as new data comes in.

The List class does not implement the IBindingList interface which supports list change notifications.
Try using the BindingList class instead:
Provides a generic collection that supports data binding.
To observe changes to the properties in your class, the class would need to implement the INotifyPropertyChanged interface:
Notifies clients that a property value has changed.

List(of ) does not support change notifications. For your purpose, change the List(of ) to a ObservableCollection(of ).

Related

Add rows to class bound datagridview

Hi I'm trying to bind a list of objects to a datagridview
Binding a existing list(Of is working but I'm trying to add or remove a object from, my dgv isn't updating.
Public Class Form1
Dim lt As New List(Of Test)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
lt.Add(New Test("Mac", 2200))
lt.Add(New Test("PC", 1100))
dgv.DataSource = lt
lt.Add(New Test("Android", 3300)) 'This line won't appear in the dgv
End Sub
End Class
Public Class Test
Public Sub New(ByVal name As String, ByVal cost As String)
_name = name
_cost = cost
End Sub
Private _name As String
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Private _cost As String
Public Property Cost() As String
Get
Return _cost
End Get
Set(ByVal value As String)
_cost = value
End Set
End Property
End Class
How can I add or remove or change a value from the dgv to the list and inverse?
NoiseBe
Change this line:
Dim lt As New List(Of Test)
To:
Imports System.ComponentModel
...
Private lt As New BindingList(Of Test)
When the collection contents will change, you should use a BindingList(Of T). This collection has events associated with it which make it aware of changes to the list contents.
If in addition to the list contents, the list items will change (like Test.Name), you should also implement INotifyPropertyChanged on the class itself.
Another way to do it:
dgv.DataSource = Nothing
lt.Add(New Test("Android", 3300))
dgv.DataSource = lt
This "resets" the DataSource so that the new contents will show up. However, it means that several other things get reset like selected items; if you are binding to a List/Combo control, you will also have to reset the ValueMember and DisplayMember properties as well.

VB.net MVC understanding and binding

I am trying to seperate my code logic from my gui as in MVC principles, what I am trying to achieve is quite simple I believe
I have my Form1, which contains a textbox and button, once the button is clicked it loads a function in my controller class which adds a string to a database using entity and then should update the textbox with this name.
I thought what I would need to do is pass the original form through and then databind to the textbox object on the form, this is where I have come unstuck though, as my logic fails...
Public Class Form1
Private mf As New MainForm(Me)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
mf.buttonClick()
End Sub
End Class
Public Class MainForm
Private Property a As Form
Public Sub New(ByVal s As Form)
a = s
End Sub
Function buttonClick() As Boolean
Dim context As TestDBEntities2 = New TestDBEntities2
Dim newCategory As tTable = New tTable
newCategory.Name = "Test1 " & Today.DayOfWeek
context.tTables.Add(newCategory)
context.SaveChanges()
Dim current As String = newCategory.Name
a.DataBindings.Add("text", "TextBox1", current)
Return True
End Function
End Class
and my error:
Cannot bind to the property or column Test1 6 on the DataSource.
Am I looking at this the right way? Or am I so far off that there is an obvious reason this doesn't work?
Any input would be appreciated! Whats the best way to pass data back to a source without returning it in as a result of a function?
You should consider changing your code a bit, so that it reflects more the MVC structure:
use Events to exchange data and indicate action triggers, instead of using the form object
normally the controller has knowledge of the form and not the other way around, so swap this in your project. This reflects also the first point
So a possible solution for a Windows Forms application could look like this:
The form that has one button and one text field, one event to signal the button click and one WriteOnly property to fill the TextBox from outside the form:
Public Class MainForm
Public Event GenerateAndShowEvent()
' allow text box filling
Public WriteOnly Property SetTextBoxContent()
Set(ByVal value)
generatedInputTextBox.Text = value
End Set
End Property
Private Sub generateAndShowButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles generateAndShowButton.Click
' forward message: inform the subscriber that something happened
RaiseEvent GenerateAndShowEvent()
End Sub
End Class
The controller class has knowledge of the form, creates it, binds (listens) to the form's button click event and makes the form ReadOnly for the world (exposes the form):
Public Class MainFormController
' the form that the controller manages
Private dialog As MainForm = Nothing
Public Sub New()
dialog = New MainForm()
' bind to the form button click event in order to generate the text and response
AddHandler dialog.GenerateAndShowEvent, AddressOf Me.GenerateAndShowText
End Sub
' allow the world to access readonly the form - used to start the application
Public ReadOnly Property GetMainForm()
Get
Return dialog
End Get
End Property
Private Sub GenerateAndShowText()
' create the text
Dim text As String = "Test test test"
' access the Database ...
' give the generated text to the UI = MainForm dialog!
dialog.SetTextBoxContent = text
End Sub
End Class
Now what left is to create first the controller, that creates the form and use the form to show it. This can be done like this:
Create an AppStarter module with a Main method:
Module AppStarter
Sub Main()
Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(False)
' create the controller object
Dim controller As MainFormController = New MainFormController()
' use the public property to get the dialog
Application.Run(controller.GetMainForm)
End Sub
End Module
In your project settings uncheck the enable application framework setting and set the AppStarter module as the start point of your project:
Now you have a Windows Form Project using the MVC pattern.
If you still want to use DataBinding for the TextBox control, then create a Data Transfer Object or DTO that represents the fields you will transfer from your controller to the form:
Public Class DataContainer
Private t As String
Private i As Integer
Public Property Text() As String
Get
Return t
End Get
Set(ByVal value As String)
t = value
End Set
End Property
Public Property Id() As Integer
Get
Return i
End Get
Set(ByVal value As Integer)
i = value
End Set
End Property
End Class
Then add a BindingSource for your TextBox and configure it to use the DTObject:
Now bind the TextBox control to the DataBinding control:
What left is to add a public setter for the TextBox data binding control in the form:
Public Property TextBoxDataSource()
Get
Return TextBoxBindingSource.DataSource
End Get
Set(ByVal value)
TextBoxBindingSource.DataSource = value
End Set
End Property
and transfer the data from the controller:
Private Sub GenerateAndShowText()
' create the text
Dim text As String = "Test test test"
' access the Database ...
' give the generated text to the UI = MainForm dialog!
'dialog.SetTextBoxContent = text
Dim data As DataContainer = New DataContainer
data.Text = text
data.Id = 1 ' not used currently
dialog.TextBoxDataSource = data
End Sub
The binding can also be set programmatically - instead of doing this over the control property window, add the following code in the constructor of the form:
Public Sub New()
InitializeComponent()
' bind the TextBox control manually to the binding source
' first Text is the TextBox.Text property
' last Text is the DataContainer.Text property
generatedInputTextBox.DataBindings.Add(New Binding("Text", TextBoxBindingSource, "Text"))
End Sub
You seem to misunderstand the Add method.
The first argument is the name of the control's property to which you are binding. This should be "Text", not "text".
The second argument is an object that contains the data you want to bind. You have passed the name of the target control, rather than the source of the data. You are also binding to the form rather than the text box. So what you have said is that you want to bind the form's text property to data that can be extracted from the string "TextBox1".
The third argument says where to go to find the data. For example, if you passed a FileInfo object for the second argument, and you wanted to bind the file's path, you would pass the string "FullName", because that is the name of the property containing the data you want. So you have told the binding to look for a property on the string class called "Test1 6", which is why you have received the error message saying it can't be found.
I think what you want is
a.TextBox1.DataBindings.Add("Text", newCategory, "Name");

MVVM Webservice not holding data returned

I would like to create an application that is gong to connect to a web service and return some data. I have been following a few tutorials and have the following code:
Public Class ItemViewModel
Implements INotifyPropertyChanged
Private _Name As String
Public Property Name() As String
Get
Return _Name
End Get
Set(ByVal value As String)
If Not value.Equals(_Name) Then
_Name = value
NotifyPropertyChanged("Name")
End If
End Set
End Property
..... along with other properties resembling the table from my database.
I then have a MainViewModel
Private _Customer As New CustomerService.Customer
Public Sub LoadData()
Dim myService As New CustomerService.CustomerClient
myService.GetCustomerByNameAsync("Andy")
AddHandler myService.GetCustomerByNameCompleted, AddressOf CustomerByName
Items.Add(NewItemViewModel With {.Name = _Customer.Name})
End Sub
Private Sub CustomerByName(sender As Object, e As CustomerService.GetCustomerByNameCompletedEventArgs)
_Customer = e.Result
End Sub
The problem i have is the service returns data when i check with WCF test tool but on this occasion when running the app i keep getting an empty object for _Customer. I have tried making it into a shared variable but nothing seems to hold the data i get from the service.
How i could hold the data in my MainViewModel?
Thanks
The problem is that GetCustomerByNameAsync execute asynchronously so Items.Add(NewItemViewModel With {.Name = _Customer.Name}) execute before the service respon and the code inside CustomerByName execute. If you move the Add code inside the event handler (CustomerByName) it should work like you want.

Best way to bind My.Settings to a datagridview, so end user can modify?

How can we databind a datagridview to some of the My.Settings (user scoped) properties so the user can edit the values? This must be to a datagridview. I know we can bind to My.Settings in a form with textboxes and so on, but in this case we just want it as list of editable strings in a datagridview.
Of course some My.Settings entries can have different datatypes which complicates matters but generally we're only working with strings and booleans.
Also, let's assume the user understands that he must enter the string "true" to set a boolean to true. No checkbox column needed.
Here's what we are using (and it works), just looking for a better, leaner way:
here's the class:
Public Class MySettingsMaint
...
then we have a bindinglist (this is probably yuk):
Private list As BindingList(Of BindingKeyValuePair)
here's what the datagridview binds to:
Public ReadOnly Property DataSource() As Object
Get
list = New BindingList(Of BindingKeyValuePair)
list.Add(New BindingKeyValuePair("PhoneExtension", My.Settings.PhoneExtension.ToString.ToLower))
list.Add(New BindingKeyValuePair("PhonePIN", My.Settings.PhonePIN.ToString.ToLower))
list.Add(New BindingKeyValuePair("PhoneEnabled", My.Settings.PhoneEnabled.ToString.ToLower))
Return From k In list Order By k.Key
Return list
End Get
End Property
...
Public Sub LoadGrid(ByVal grd As DataGridView) Implements
/some stuff here to create two DataGridViewColumns
/one bound to Key, the other bound to Setting
End Sub
more yuk here, to save back to My.Settings:
Public Sub Save() Implements IMaintainable.Save
My.Settings.PhoneExtension = (From x As BindingKeyValuePair In list Where x.Key = "PhoneExtension" Select x.Value.ToLower).ToList(0)
My.Settings.PhonePIN = (From x As BindingKeyValuePair In list Where x.Key = "PhonePIN" Select x.Value.ToLower).ToList(0)
My.Settings.PhoneEnabled = (From x As BindingKeyValuePair In list Where x.Key = "PhoneEnabled" Select x.Value.ToLower).ToList(0) = "true"
My.Settings.Save()
End Sub
the private class required by the above class:
Private Class BindingKeyValuePair
Sub New(ByVal k As String, ByVal v As String)
Key = k
Value = v
End Sub
Private _Key As String
Public Property Key() As String
/basic getsetter
End Property
Private _Value As String
Public Property Value() As String
/basic getsetter
End Property
End Class
You should use the PropertyGrid control? It will help with regard to supporting richer property types.

Vb.net Custom Class Property to lower case

I am trying to create a settings class.
The Property Test() is a list of strings.
When I add a string such as: t.test.Add("asasasAAAAA")
I want it to autmatically turn lowercase.
For some reason it is not. Any Ideas?
p.s.
using t.test.Add(("asasasAAAAA").ToLower) will not work for what I need.
Thank you.
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim t As New Settings
t.test.Add("asasasAAAAA")
t.test.Add("aBBBBBAAAAA")
t.test.Add("CCCCCsasAAAAA")
End Sub
End Class
Public Class Settings
Private strtest As New List(Of String)
Public Property test() As List(Of String)
Get
Return strtest
End Get
Set(ByVal value As List(Of String))
For i As Integer = 0 To value.Count - 1
value(i) = value(i).ToLower
Next
strtest = value
End Set
End Property
End Class
ashakjs
That's the reason: set accessor of your property is actually never called.
when you use t.test.Add("asasasAAAAA") you are actually calling a get accessor, which returns a list, after that specified string is added to this list, so .ToLower function is never called.
Simple way to fix this:
Dim list as New List(Of String)
list.Add("asasasAAAAA")
list.Add("aBBBBBAAAAA")
list.Add("CCCCCsasAAAAA")
t.test = list
Alternatively, you can implement your own string list (easiest way - inherit from Collection (Of String)), which will automatically convert all added string to lower case.
What you are trying to do and what you are doing don't match. To do what you want, you need to create your own collection class extending the generic collection - or provide a custom method on your settings class which manually adjusts the provided string before adding it to the local (private) string collection.
For an example of the second option, remove the public property of the settings class which exposes the list of string and use a method like the following:
Public Sub Add(ByVal newProp As String)
strtest.Add(newProp.toLower())
End Sub