Tuesday, October 20, 2009

Automatic Setting of MaxLength Property for Binded Controls

Following example demonstrates smart setting of textBox's MaxLength property, according to the length of binded data source field.
It might be useful in order to prevent exceptions, caused by entering a text, which exceeds specified maximum field size within your data source.
All you should do is to subscribe to DataBindings.CollectionChanged event of your control and put this simple code:

private void DataBindings_CollectionChanged(object sender, CollectionChangeEventArgs e)
{
if (e != null && e.Action == CollectionChangeAction.Add)
{
int bindedFieldMaxLength = this.MaxLength;
Binding bindingObj = (e.Element as Binding);
if (bindingObj != null)
{
if (bindingObj.DataSource != null &&
bindingObj.BindingMemberInfo != null)
{
DataTable sourceTable = (bindingObj.DataSource as DataTable);
DataView sourceView = (bindingObj.DataSource as DataView);
BindingMemberInfo bindingMemberInfoObj =
bindingObj.BindingMemberInfo;
if ((sourceTable != null sourceView != null) &&
bindingMemberInfoObj != null)
{
string bindedFieldName = bindingMemberInfoObj.BindingField;
if (!string.IsNullOrEmpty(bindedFieldName))
{
if ( sourceTable != null &&
sourceTable.Columns[bindedFieldName].MaxLength > 0)
{
bindedFieldMaxLength =
sourceTable.Columns[bindedFieldName].MaxLength;
}
if(sourceView != null &&
sourceView.Table.Columns[bindedFieldName].MaxLength > 0)
{
bindedFieldMaxLength =
sourceView.Table.Columns[bindedFieldName].MaxLength;
}
if (this.MaxLength != bindedFieldMaxLength)
{
this.MaxLength = bindedFieldMaxLength;
}
}
}
}
}
}


That's it...

No comments:

Post a Comment