无法绑定数据源中的属性或列"Column Name"。参数名称:dataMember。

9

我需要翻译两个DTO类:

public class AddressDto
{
    public string Street { get; set; }
    public string City { get; set; }
    public string PostCode { get: set: }
}

public class CustomerDto
{
    public int Number{ get; set; }
    public string Name { get; set; }
    public AddressDto Address { get: set: }

    public CustomerDto() 
    {
        Address = new AddressDto();
    }
}

我有一个带绑定源的表单,它绑定到CustomerDto。我还有一个具有地址字段的自定义控件。这个自定义控件有一个绑定源,绑定到AddressDto。控件的文本框正确地绑定到地址属性。

该控件公开了以下属性:

[Bindable(BindableSupport.Yes, BindingDirection.TwoWay)]
[Browsable(false)]
public object Address
{
    get { return bindingSource.DataSource; }
    set { bindingSource.DataSource = value; }
}

在一台机器上,CheckBinding() 没有出现任何错误。然而,在另一台机器上,在运行时尝试打开表单时,会出现上述异常。在设计时,一切都正常。
该控件有 3 个 TextBoxes,设计师添加了以下绑定:
this.bindingSource.AllowNew = true;
this.bindingSource.DataSource = typeof(AddressDto);

this.txtStreet.DataBindings.Add(new Binding("Text", this.bindingSource, "Street", true));
this.txtCity.DataBindings.Add(new Binding("Text", this.bindingSource, "City", true));
this.txtPostCode.DataBindings.Add(new Binding("Text", this.bindingSource, "PostCode", true));

有任何想法,问题可能出在哪里?

你在绑定中使用了属性路径吗?如果是,那么这可能类似于此问题 Binding and Polymorphism - Cannot bind property or column (Winforms) - Ivan Stoev
@IvanStoev 不是的。我没有使用属性路径。 - Ivan-Mark Debono
1
能否提供一些 [mcve] 呢? - Ivan Stoev
1个回答

5

我将代码修改为:

    [Bindable(BindableSupport.Yes, BindingDirection.TwoWay)]
    [Browsable(false)]
    public object Address
    {
        get { return bindingSource.DataSource; }
        set 
        {
            if (value != null && value != System.DBNull.Value)
                bindingSource.DataSource = value;
            else
                bindingSource.DataSource = typeof(AddressDto);
        }
    }

值为System.DBNull。经过上述更改,异常不再抛出。

这解决了问题。然而,为什么值是DBNull仍然不清楚,因为我正在使用纯POCO类作为我的数据源来绑定。


3
WinForms数据绑定最初是为了操作DataTable而构建的,后来才添加了它绑定对象的能力。这就是为什么你会得到一个DBNull而不是null的原因。 - Nickolai Nielsen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接