问题
I have a DataGridView which uses a BindingSource. This BindingSource points to a read-only property, which is a collection of department
objects. When I programmatically add a department to the property, I am having trouble getting the DataGridView to redraw itself + show the new department.
If I set a breakpoint, I verify that the property has the new department; yet the DataGridView does not draw it. If I navigate away from the tab, and then back, the DataGridView displays the new department.
My question is essentially, how can I programmatically trigger whatever happens when I navigate away from and then back to the DataGridview, to force it to redraw (or force its BindingSource to update)? I've tried all the following:
AffectedDepartmentsBindingSource.CancelEdit()
AffectedDepartmentsBindingSource.EndEdit()
AffectedDepartmentsBindingSource.ResetBindings(False)
AffectedDepartmentsBindingSource.ResetBindings(True)
AffectedDepartmentsDataGridView.Refresh()
AffectedDepartmentsDataGridView.Update()
AffectedDepartmentsDataGridView.Hide()
AffectedDepartmentsDataGridView.Show()
Here's the property:
Public ReadOnly Property affectedDepartments As SortableBindingList(Of Department)
Get
Dim uniqueDeptIds As New ArrayList
Dim _affectedDepartments As New SortableBindingList(Of Department)
'Go through products
For Each p As product In products.Where(Function(pr) pr.isNotACopy)
If Not uniqueDeptIds.Contains(p.cs_dept_id) Then
uniqueDeptIds.Add(p.cs_dept_id)
Dim d As New Department With {
.schedule = Me,
.name = p.department,
.cs_dept_id = p.cs_dept_id
}
_affectedDepartments.Add(d)
End If
Next
'Add temp departments
If _tempDepartment IsNot Nothing Then
_affectedDepartments.Add(_tempDepartment)
End If
Return _affectedDepartments
End Get
End Property
回答1:
Like this:
Me.DataGridView1.Invalidate()
Edit
The reason why you don't see the added items is because you create a new instance each time.
You should do it like this:
Public ReadOnly Property affectedDepartments As SortableBindingList(Of Department)
Get
Dim uniqueDeptIds As New ArrayList
If (_affectedDepartments Is Nothing) Then
_affectedDepartments = New SortableBindingList(Of Department)
End If
'Go through products
For Each p As product In products.Where(Function(pr) pr.isNotACopy)
If Not uniqueDeptIds.Contains(p.cs_dept_id) Then
uniqueDeptIds.Add(p.cs_dept_id)
Dim d As New Department With {
.schedule = Me,
.name = p.department,
.cs_dept_id = p.cs_dept_id
}
_affectedDepartments.Add(d)
End If
Next
'Add temp departments
If _tempDepartment IsNot Nothing Then
_affectedDepartments.Add(_tempDepartment)
End If
Return _affectedDepartments
End Get
End Property
Private _affectedDepartments As SortableBindingList(Of Department)
回答2:
you can refresh the DataGridView
Datagrid.Items.Refresh()
来源:https://stackoverflow.com/questions/20843313/how-can-i-force-a-datagridview-to-redraw