Reputation: 45
I have a textbox and an object is bound to the text. In code I need to find which object was bound.
I'm using a Windows.Forms.TextBox I have the DataBinding-Text bound to any objects name field. This is done at design time. In code I need to figure out what the object is that is bound to this TextBox.
Upvotes: 1
Views: 2079
Reputation: 112402
Query the DataBindings
of the textbox. The DataSource
of the Binding
can contain different things:
Type
object describing the type of object the property can bind to. This can be the case when the form is loading and no object has been attached yet.BindingSource
. In this case, we must query the DataSource
of this binding source.null
.In case we have a BindingSource
, we can again have a Type
object. To get the object type a binding is supposed to bind to, I wrote this helper method which calls itself recursively. (using C#7.0 syntax)
private Type GetBoundType(object dataSource)
{
switch (dataSource) {
case Type type:
return type;
case BindingSource bindingSource:
return GetBoundType(bindingSource.DataSource);
default:
return dataSource?.GetType();
}
}
You can call it like this (using C#7.0 syntax):
Binding binding = textBox.DataBindings["Text"];
if (binding != null && GetBoundType(binding.DataSource) == expectedType) {
...
}
If you know that an actual data object has been bound to the data source you can get it with:
object entity = binding.DataSource is BindingSource bs ? bs.DataSource : binding.DataSource;
Upvotes: 0
Reputation: 11
Just in case anybody still needs to know this: textBox1.DataBindings("Text").BindingMemberInfo.BindingField
Tim
Upvotes: 1
Reputation: 1382
In your code at runtime, assuming your bound object is some MyObject:
if (textBox1.DataBindings.Count == 1)
{
var myObj = textBox1.DataBindings[0].DataSource as MyObject;
if (myObj != null)
// do something with the bound object
else
// well, found data bound object but it was not a MyObject... Handle as appropriate
}
Hope this helps.
Upvotes: 1
Reputation: 17012
Is the object stored in the tag of the Textbox?
object o = textbox.Tag;
Upvotes: 0