0

I have a variety of Textboxes that are created dynamically on my form, when they are created databindings are added binding the textbox to a property in my class.

I need to be able to get a reference to the Textbox however I only know the property that textbox is bound to. So is it possible to get a reference to the textbox knowing only the name of the property it's bound to.

I hope I've explained this properly!

AlbinoMonkey
  • 11
  • 1
  • 1
  • 1
    You can use Control.Tag to store this meta-information. – sgud Oct 18 '12 at 08:32
  • Can you see the textbox on the forms designer? – JMK Oct 18 '12 at 08:35
  • No I cant see the textbox(s) in the forms designer. They are generated at runtime. – AlbinoMonkey Oct 18 '12 at 09:09
  • 2
    I've solved the problem by looping through all the controls for the parent TableLayoutPanel if the control was a textbox then get the binding. From the binding I could check the BindingMemberInfo.BindingMember to check the bound property Name – AlbinoMonkey Oct 18 '12 at 09:46

1 Answers1

4

If I understand correctly, you can try this method at Form class:

public Control GetControlByDataBinding(string key)
{
    foreach (Control control in Controls)
    {
        foreach (Binding binding in control.DataBindings)
        {
            if (binding.PropertyName == key) return control;
        }
    }

    return null;
}

Or even better with Linq:

public Control GetControlByDataBinding(string key)
{
    return 
        Controls
        .Cast<Control>()
        .FirstOrDefault(control => 
            control.DataBindings
            .Cast<Binding>()
            .Any(binding => binding.PropertyName == key));
}
Caverna
  • 461
  • 9
  • 16
  • 2
    thank you, but `binding.PropertyName` returns `"Text"` for textboxes. As stated by the OP above, the bound field is at `binding.BindingMemberInfo.BindingField` or `BindingMember` – Ivan Ferrer Villa Feb 10 '15 at 12:56