Attention: We are retiring the ASP.NET Community Blogs. Learn more >

Nifty loop for databinding all controls on a form

I found myself databinding each control on my form one by one.  To much time, too much work.  Instead, I did this:

Dim ctrl As Control

For Each ctrl In Controls

    If TypeOf ctrl Is TextBox Then

        Dim txtName As String = ctrl.Name.ToString

        txtName = LCase(txtName.Remove(0, 3))

        ctrl.DataBindings.Add("Text", tblNames, txtName)

    ElseIf TypeOf ctrl Is ListBox Then

        ' bind to listbox here

End If

The trick here is to name your controls the same name as the datacolumn.  In the above, I name them "txt"columnname and then strip off the "txt" and make sure it's lowercase as we use lowercase for all of our columnnames.

 

 

No Comments