user698625
user698625

Reputation: 45

How to find what object is bound to a winform text box

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

Answers (5)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112402

Query the DataBindings of the textbox. The DataSource of the Binding can contain different things:

  • A 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.
  • A BindingSource. In this case, we must query the DataSource of this binding source.
  • A data object or 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

Tim Webster
Tim Webster

Reputation: 11

Just in case anybody still needs to know this: textBox1.DataBindings("Text").BindingMemberInfo.BindingField
Tim

Upvotes: 1

pelazem
pelazem

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

AJ.
AJ.

Reputation: 16719

Try querying the textbox's DataBindings property at runtime.

Upvotes: 1

GameScripting
GameScripting

Reputation: 17012

Is the object stored in the tag of the Textbox?

object o = textbox.Tag;

Upvotes: 0

Related Questions