您好我试图将对象列表绑定到datagridview 绑定现有列表(Of is正在运行但我尝试添加或删除对象,我的dgv不会更新。
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
如何在dgv中添加,删除或更改值到列表中?
NoiseBe
答案 0 :(得分:0)
更改此行:
Dim lt As New List(Of Test)
要:
Imports System.ComponentModel
...
Private lt As New BindingList(Of Test)
当收集内容发生变化时,您应该使用BindingList(Of T)
。此集合具有与之关联的事件,使其了解列表内容的更改。
如果除了列表内容之外,列表 items 将会更改(如Test.Name),您还应该在类本身上实现INotifyPropertyChanged
另一种方法:
dgv.DataSource = Nothing
lt.Add(New Test("Android", 3300))
dgv.DataSource = lt
这会“重置”DataSource
,以便显示新内容。但是,这意味着其他几件事情会像所选项目一样重置;如果您绑定到List / Combo控件,则还必须重置ValueMember
和DisplayMember
属性。