当我更新数据源时,我试图让 datagridview 更新,但我没有任何运气。
这是我的绑定:
Private _dgbNews As SortableBindingList(Of SalesMessageRecord)
Private Sub SalesMessageScreen_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
'_dgbNews.RaiseListChangedEvents = True
_dgbNews = AllNews()
BindingSource1.DataSource = AllNews()
DataGridView1.DataSource = BindingSource1
MassageDemRows()
End Sub
这是 AllNews()
:
Public Function AllNews() As SortableBindingList(Of SalesMessageRecord)
Dim sm = New SortableBindingList(Of SalesMessageRecord)
Dim allnewsitems = News.GetAllNewsItems(Configuration.CompanyID).ToList()
For Each allnewz As News In allnewsitems
Dim smr = New SalesMessageRecord
smr.Body = allnewz.NewsBody
smr.CorporationId = CType(allnewz.CorporationId, Guid)
smr.Expiration = allnewz.Expiration
smr.IsActive = allnewz.IsActive
smr.NewsId = allnewz.NewsId
smr.Title = allnewz.NewsTitle
smr.SortOrder = allnewz.OrderNumber
smr.TokenId = allnewz.TokenId
smr.IsNew = False
sm.Add(smr)
Next
Return sm
End Function
这就是我试图更新它的地方:
Private Sub button_Save_Click(sender As System.Object, e As System.EventArgs) Handles button_Save.Click
If _currentRow < 0 Then
Return
End If
_dgbNews(_currentRow).Expiration = datetimepicker_ExpirationDate.Value
_dgbNews(_currentRow).SortOrder = CInt(numericupdown_SortNumber.Value)
_dgbNews(_currentRow).IsActive = checkbox_Active.Checked
_dgbNews(_currentRow).Body = richtextbox_Body.Text
_dgbNews(_currentRow).Title = textbox_Title.Text
DataGridView1.Refresh()
News.UpdateNewsRecord(_dgbNews(_currentRow).NewsId,
_dgbNews(_currentRow).Expiration,
_dgbNews(_currentRow).SortOrder,
_dgbNews(_currentRow).IsActive,
_dgbNews(_currentRow).Body,
_dgbNews(_currentRow).Title)
End Sub
数据库正在更新而没有问题,但 datagridview 不会更新。
好的,我会解决这个问题的。 Bindingsources 在与 DGV 一起使用时非常有用。然而,他们往往很敬畏,因为他们不提供任何信息,不管他们为什么不工作。
首先我会说你的绑定源有错误的数据源。
如您所见,您将 AllNews() 作为数据源。但是您将内容添加到 _dgbNews 并期望 Allnews() 发生变化。 Protip,它没有。如果您要将 DataSource 设置为此:
那么至少您应该在更新列表时期待一些变化。现在这就是你真正想念的。在按钮保存中单击您将一个项目添加到列表中,如果您完成了上述操作,现在就可以了。但是等等,数据源改变了,但什么也没有发生。这是因为您没有告诉 datagridview 进行更改。使 Bindingsource 告诉它连接到的所有内容进行更新。有了这个:
这比 DGV.Refresh(现在可能工作)更好,因为您的绑定源可以附加到其他东西(我知道不是,但供将来参考)。
试试这个,看看它是否会更好。