繁体   English   中英

将TextBox.Text绑定到DataSet.DataSetName

[英]Bind TextBox.Text to DataSet.DataSetName

我试图将TextBoxText属性绑定到DataSetDataSetName属性。

我懂了

System.ArgumentException:'无法绑定到数据源上的属性或列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;
  • node.TableGroup是正确的(不为null,指向右上方的DataSet

一旦真正绘制了TextBox ,我就会得到上述异常。

我在设计器中使用Windows窗体,因此自动生成了前两行代码。

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM