【问题标题】:Bind TextBox.Text to DataSet.DataSetName将 TextBox.Text 绑定到 DataSet.DataSetName
【发布时间】:2019-01-22 17:50:42
【问题描述】:

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

我明白了

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 窗体,所以前两行代码是自动生成的。

【问题讨论】:

  • 我们可以看示例代码吗?
  • 您不能将文本绑定到一个属性,然后在您的 VM 中设置 DataSetName 的值吗?
  • 这应该相对简单:参见msdn.microsoft.com/en-us/library/…。如果您在使用 BindingSource 时遇到问题,也许您可​​以尝试使用 DataTable?没有代码很难确切地知道你在做什么。您是在设置标记还是代码隐藏?
  • @DanielLoudon 已编辑

标签: c# .net winforms data-binding dataset


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-20
    • 2014-12-08
    • 2015-11-25
    • 2011-06-18
    • 2010-10-02
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    相关资源
    最近更新 更多