Set Focus to Data Bound Control w/ BrokenRule

Set Focus to Data Bound Control w/ BrokenRule

Old forum URL: forums.lhotka.net/forums/t/3920.aspx


honus posted on Tuesday, November 20, 2007

I am doing some custom validation using the BrokenRulesCollection on a WinForm, and simply put, if there are any broken rules in the collection, I want to alert the user regarding the first broken rule in the collection, and then set the form focus to the correlating control.

Here is what I have so far:

If mObject.BrokenRulesCollection.Count > 0 Then
   Dim tmpRule As Validation.BrokenRule = mObject.BrokenRulesCollection(0)
   MessageBox.Show(tmpRule.Description & "!", "Data Entry Error")

   'this is where I need help in setting focus to the data-bound control
End If

I am guessing that I can do something with BrokenRule.Property in conjunction with the BindingSource, but I am yet to figure this out.  I have thought about looping through all of the controls and doing something with the DataBindings collection, but there is some pretty intense nesting going on (textboxes within panels within tabcontrols), so I have tried to avoid this, as I am sure there is a more simple way.  Any help is appreciated.

honus replied on Tuesday, November 20, 2007

Here is what I came up with.  Let me know if you have something better/more efficient.

If mObject.BrokenRulesCollection.Count > 0 Then
   Dim tmpRule As Validation.BrokenRule = mObject.BrokenRulesCollection(0)
   MessageBox.Show(tmpRule.Description & "!", "Data Entry Error")

   setFieldFocus(Me, tmpRule.Property)
End If

Private Sub setFieldFocus(ByVal parentContainer As Control, ByVal propName As String)
   
For Each tmpControl As Control In parentContainer.Controls
      'allow for some recursion in case of nested child controls

      
If tmpControl.Controls.Count > 0 Then setFieldFocus(tmpControl, propName)

      For Each tmpBinding As Binding In tmpControl.DataBindings
         
If tmpBinding.BindingMemberInfo.BindingField.Equals(propName) Then
            
tmpBinding.Control.Focus()
            
Exit Sub
         
End If
      
Next
   Next
End Sub

Copyright (c) Marimer LLC