0

我有一个 GUI,允许用户选择要查看/编辑的报告。当用户选择一个报表时,它会显示报表中的项目。该项目有许多属性 - 其中大部分都正确绑定。属性之一是 Owner,它绑定到 ComboBoxColumn。

  • 报告
    • 项目
      • 所有者

我已经做了几次与此非常相似的事情,并且在设置DataPropertyName, DataSource,ValueMember和时没有任何问题DisplayMember。唯一的区别是,这一次它实际上有一个对象实例,而不是Item类型。OwnderIDOwner

我在另一篇文章中看到了通过为列表中绑定的项目提供自引用属性来解决此问题的建议,该属性允许它们返回自己以设置ValueMember

但是,当我以这种方式绑定它时:

OwnerColumn.DataPropertyName = "Owner"
OwnerColumn.DataSource = ownersBindingSource1
OwnerColumn.ValueMember = "Self"
OwnerColumn.DisplayMember = "OwnerName"

我收到很多错误,例如:

Unable to cast object of type 'System.String' to type 'Owner'.

和:

The following exception occurred in the DataGridView:

System.ArgumentException: DataGridViewComboBoxCell value is not valid.

To replace this default dialog please handle the DataError event.

通过像这样绑定它,我能够解决其中的一些错误:

OwnerColumn.DataPropertyName = "Owner"
OwnerColumn.DataSource = ownersBindingSource1

并且还通过使显示ToString上的功能成为属性。不过,这似乎很老套——而且我认为我误解了一些基本的东西,因为它仍然无法正常运行。任何帮助将非常感激。OwnerOwnerName

4

1 回答 1

0

我发现我的很多错误都来自我对阅读过的各种文章的误解以及草率的代码。

我忽略了在一些属性上指定返回类型,选项显式/选项严格都关闭了,并且我的设计器出现了一些损坏,并且一些列被重复了。

我最喜欢的一个解决方案是:http ://code.google.com/p/systembusinessobjects/source/browse/trunk/System.BusinessObjects.Framework/Data/SafeBindingLists.cs 。不幸的是,这需要 Castle 代理和旧版本的 NHibernate。

这是我找到的简单解决方案:

问题是您不能将列表与多种类型的对象绑定。目标是能够让 ComboBox 直接设置它与另一个对象绑定的对象的属性值。

我选择使用 View 对象,并将列表绑定到该对象。

查看对象:

Public Class OwnerView
    Private _owner As Owner

    Public ReadOnly Property OwnerId As Integer
        Get
            Return _owner.OwnerId
        End Get
    End Property

    Public ReadOnly Property OwnerName As String
        Get
            Return _owner.OwnerName
        End Get
    End Property

    Public ReadOnly Property OwnerAbbreviation As String
        Get
            Return _owner.OwnerAbbreviation
        End Get
    End Property

    Public Overridable ReadOnly Property Self As Owner
        Get
            Return _owner
        End Get
    End Property

    Public Sub New(ByVal owner As Owner)
        _owner = owner
    End Sub

End Class

捆绑:

With OwnerColumn
    .SortMode = DataGridViewColumnSortMode.Automatic
    .ReadOnly = False
    .Name = "OwnerColumn"
    .HeaderText = "Owner"

    Dim bs As New BindingSource()

    For Each co As Owner In Owners
        bs.Add(New OwnerView(co))
    Next

    .DataPropertyName = "Owner"
    .DataSource = bs
    .ValueMember = "Self"
    .DisplayMember = "OwnerName"

    ItemDataGridView.Columns.Add(OwnerColumn)
End With
于 2012-01-25T04:25:26.690 回答