如何强制DataGridView重绘?

时间:2013-12-30 16:19:24

标签: .net vb.net winforms visual-studio-2010

我有一个使用BindingSource的DataGridView。此BindingSource指向只读属性,该属性是department个对象的集合。当我以编程方式向属性添加部门时,我无法让DataGridView重绘自己+显示新部门。

如果我设置断点,我会验证该属性是否具有新部门;但DataGridView不会绘制它。如果我离开选项卡,然后返回,则DataGridView将显示新部门。

我的问题基本上是,如何以编程方式触发当我离开然后返回到DataGridview 时发生的任何事情,强制它重绘(或强制其BindingSource更新)?我已经尝试了以下所有方法:

AffectedDepartmentsBindingSource.CancelEdit()
AffectedDepartmentsBindingSource.EndEdit()
AffectedDepartmentsBindingSource.ResetBindings(False)
AffectedDepartmentsBindingSource.ResetBindings(True)

AffectedDepartmentsDataGridView.Refresh()
AffectedDepartmentsDataGridView.Update()
AffectedDepartmentsDataGridView.Hide()
AffectedDepartmentsDataGridView.Show()

这是属性:

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

2 个答案:

答案 0 :(得分:3)

像这样:

Me.DataGridView1.Invalidate()

修改

您没有看到添加的项目的原因是您每次都创建一个新实例。

你应该这样做:

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)

答案 1 :(得分:0)

您可以刷新DataGridView

Datagrid.Items.Refresh()