locked
Setting TextBox MaxLength from DataColumn MaxLength RRS feed

  • Question

  • I've got a TextBox bound to a column in a DataTable. I want to programatically set the MaxLength of the TextBox to the MaxLength of the corresponding DataColumn. The DataSource Wizard (surprisingly) doesn't do this. How can I do it?

     

    Monday, February 6, 2006 4:16 PM

Answers

  • 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

     

    Saturday, March 18, 2006 2:14 AM