You can use reflection or type descriptor to get information about a type. Where and when you need to do that, depends to the implementation.
Since the data source of your data-binding can be any object like a class or a binding source, it's more flexible and extensible to rely on type descriptors. For example if you want to call a method to apply maxlength by just passing the TextBox
to the method like this:
ApplyMaxLengthToTextBox(textBox1);
Then you can create the method this way:
//using System.Linq;
public void ApplyMaxLengthToTextBox(TextBox txt)
{
var binding = txt.DataBindings["Text"];
if (binding == null)
return;
var bindingManager = binding.BindingManagerBase;
var datasourceProperty = binding.BindingMemberInfo.BindingField;
var propertyDescriptor = bindingManager.GetItemProperties()[datasourceProperty];
var maxLengthAttribute = propertyDescriptor.Attributes.Cast<Attribute>()
.OfType<MaxLengthAttribute>().FirstOrDefault();
if (maxLengthAttribute != null)
txt.MaxLength = maxLengthAttribute.Length;
}
To test it when binding to an object:
textBox1.DataBindings.Add("Text", new MySampleModel(), "SomeProperty");
ApplyMaxLengthToTextBox(textBox1);
To test it when binding to a BindingSource
:
var bs = new BindingSource();
bs.DataSource = new MySampleModel();
textBox1.DataBindings.Add("Text", bs, "SomeProperty");
ApplyMaxLengthToTextBox(textBox1);