简体   繁体   中英

Bind TextBox.Text to DataSet.DataSetName

I am trying to bind a TextBox 's Text property to a DataSet 's DataSetName property.

I get

System.ArgumentException: 'Cannot bind to the property or column DataSetName on the DataSource. Parameter name: dataMember'

If there a way to bind a single text box in this way? I think it has something to do with the fact that DataSet is a collection, so the BindingSource is expecting to have a table bound with it, not a text box.

Can I achieve this without creating a "container" class to hold my DataSetName property and a DataSet ?

Edit

It was silly of me to not include any code. So here you go:

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 is correct (not null, points top the right DataSet )

Once the TextBox is actually painted, I get the above exception.

I am using Windows Forms with the designer, so the two first lines of code are automatically generated.

The CurrencyManager uses ListBindingHelper.GetListItemProperties(yourDataset) to get its properties and since it doesn't return any property because of its type descriptor, then the data-binding fails.

You can expose DataSet properties in a different way by using a wrapper around data set, implementing a custom type descriptor to provide data set properties:

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

Then use it this way:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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