c# - 将 TextBox.Text 绑定到 DataSet.DataSetName
问题描述
我正在尝试将 aTextBox
的Text
属性绑定到 aDataSet
的DataSetName
属性。
我明白了
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;
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);
推荐阅读
- javascript - 跟踪更改对象的自定义钩子
- postgresql - PostgreSQL 安装程序无法在 Windows 10 上启动
- kubernetes - 有没有办法限制与 Spacy、Torch 等共享的 vgpu 上的 per_process 内存?
- c++ - 如何设置参数以使用 clang::tooling::runToolOnCodeWithArgs 编译 MacOS 代码?
- php - 使用 PHPUnit 10 模拟类时如何最好地保留一些方法
- sql-server - 使用子查询或 CTE 进行 SQL Server 更新,需要保证竞争条件安全
- python - 如何安排 conda env 中的 python 脚本每 n 分钟运行一次?
- php - 当控制器中有进程时,Laravel 卡住了
- python - PyQt5 窗口出现空
- html - 在 Crome 上显示黑屏的 html 视频