Here's the answer
private void SetLengths(Control cp) {
foreach (Control c in cp.Controls)
if (c is TextBox) {
Binding b = c.DataBindings["Text"];
if (b != null) {
BindingSource bs = (BindingSource) b.DataSource;
(c as TextBox).MaxLength = ((DataSet) bs.DataSource).Tables[bs.DataMember].Columns[b.BindingMemberInfo.BindingField].MaxLength;
}
}
else if (c is RichTextBox) {
Binding b = c.DataBindings["Text"];
if (b != null) {
BindingSource bs = (BindingSource) b.DataSource;
(c as RichTextBox).MaxLength = ((DataSet) bs.DataSource).Tables[bs.DataMember].Columns[b.BindingMemberInfo.BindingField].MaxLength;
}
}
}
or
Private Sub SetLengths(ByVal cx as Control)
For Each c As Control In cx.Controls
If TypeOf c Is TextBox Then
Dim b As Binding = c.DataBindings("Text")
If Not b Is Nothing Then
Dim bs As BindingSource = DirectCast(b.DataSource, BindingSource)
Dim tb As TextBox = DirectCast(c, TextBox)
Dim ds As DataSet = DirectCast(bs.DataSource, DataSet)
tb.MaxLength = ds.Tables(bs.DataMember).Columns(b.BindingMemberInfo.BindingField).MaxLength
End If
ElseIf TypeOf c Is RichTextBox Then
Dim b As Binding = c.DataBindings("Text")
If Not b Is Nothing Then
Dim bs As BindingSource = DirectCast(b.DataSource, BindingSource)
Dim tb As TextBox = DirectCast(c, TextBox)
Dim ds As DataSet = DirectCast(bs.DataSource, DataSet)
tb.MaxLength = ds.Tables(bs.DataMember).Columns(b.BindingMemberInfo.BindingField).MaxLength
End If
End If
Next
End Sub