更新时间:2023-12-06 17:15:04
更改此行:
Dim lt作为新列表(测试)
To:
导入System.ComponentModel
...
私人lt作为新的BindingList(测试)
当集合内容将更改时,应使用 BindingList(Of T)
。
如果除了列表内容,列表 将会改变(如Test.Name),您也应该在类本身上实现 INotifyPropertyChanged
。
另一种方法:
dgv.DataSource =没有
lt.Add(新测试(Android,3300))
dgv.DataSource = lt
这会重置 DataSource
,以便显示新内容。然而,它意味着其他几件事情被重置像选定的项目;如果您绑定到List / Combo控件,您还必须重置 ValueMember
和 DisplayMember
属性。
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.