首页 > 解决方案 > 将 TextBox.Text 绑定到 DataSet.DataSetName

问题描述

我正在尝试将 aTextBoxText属性绑定到 aDataSetDataSetName属性。

我明白了

System.ArgumentException: '无法绑定到 DataSource 上的属性或列 DataSetName。参数名称:dataMember'

如果有办法以这种方式绑定单个文本框?我认为这与DataSet集合的事实有关,因此BindingSource期望有一个与之绑定的表格,而不是文本框。

我可以在不创建“容器”类来保存我的DataSetName财产的情况下实现这一点DataSet吗?

编辑

不包含任何代码是我的愚蠢。所以你去:

this.tableGroupBindingSource.DataSource = typeof(DataSet);
...
this.TableGroupNameTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.tableGroupBindingSource, "DataSetName", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
...
tableGroupBindingSource.DataSource =    node.TableGroup;

一旦TextBox实际绘制,我得到上述异常。

我在设计器中使用 Windows 窗体,所以前两行代码是自动生成的。

标签: c#.netwinformsdata-bindingdataset

解决方案


用于获取其属性的CurrencyManager用途ListBindingHelper.GetListItemProperties(yourDataset),并且由于它的类型描述符,它不返回任何属性,因此数据绑定失败。

您可以通过使用数据集的包装器以不同的方式公开DataSet属性,实现自定义类型描述符以提供数据集属性:

using System;
using System.ComponentModel;
public class CustomObjectWrapper : CustomTypeDescriptor
{
    public object WrappedObject { get; private set; }
    public CustomObjectWrapper(object o) : base()
    {
        WrappedObject = o ?? throw new ArgumentNullException(nameof(o));
    }
    public override PropertyDescriptorCollection GetProperties()
    {
        return this.GetProperties(new Attribute[] { });
    }
    public override PropertyDescriptorCollection GetProperties(Attribute[] attributes)
    {
        return TypeDescriptor.GetProperties(WrappedObject, true);
    }
    public override object GetPropertyOwner(PropertyDescriptor pd)
    {
        return WrappedObject;
    }
}

然后以这种方式使用它:

var myDataSet = new DataSet("myDataSet");
var wrapper = new CustomObjectWrapper(myDataSet);
textBox1.DataBindings.Add("Text", wrapper, "DataSetName", true, 
    DataSourceUpdateMode.OnPropertyChanged);

推荐阅读