将 TextBox.Text 绑定到 DataSet.DataSetName



我正在尝试将TextBoxText属性绑定到DataSetDataSetName属性。

我得到

System.ArgumentException:"无法绑定到数据源上的属性或列 DataSetName。 参数名称:数据成员'

有没有办法以这种方式绑定单个文本框?我认为这与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是正确的(不为空,点在右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);

最新更新