ADO.NET Programming in Visual Basic .NET By Steve Holzner, Bob Howell
Table of Contents
Chapter 11. Creating Your Own Data Control
Next let's fill in the code for the NavButtons event procedure. The code appears as follows :
Private Sub NavButtons(ByVal sender As Object, ByVal e As EventArgs) Dim intNewRow As Integer Try Me.ParentForm.BindingContext(mDataSet, _ mintBoundTable).EndCurrentEdit() intNewRow = Me.ParentForm.BindingContext(Me).Position Select Case CType(sender, Button).Name Case "cmdFirst" intNewRow = 0 Case "cmdPrevious" If intNewRow > 1 Then itNewRow -= 1 Else intNewRow = 0 End If Case "cmdNext" If intNewRow < _ mDataSet.Tables(mintBoundTable).Rows.Count - 1 Then intNewRow += 1 Else intNewRow = _ mDataSet.Tables(mintBoundTable).Rows.Count - 1 End If Case "cmdLast" intNewRow = mDataSet.Tables(mintBoundTable).Rows.Count - 1 End Select If Me.ParentForm Is Nothing Then Exit Sub Me.ParentForm.BindingContext(Me).Position = intNewRow RaiseEvent PositionChanged(intNewRow) UpdatePosition() Catch errobj As Exception Throw errobj End Try End Sub
The first line after the Try statement ends any pending edits on the parent form. We have to use the binding context of the parent form because that is where the data is displayed. If we used the binding context of the UserControl it would not do anything because no edits were made in the UserControl itself. Next we get the current position of the data row. Again we use the parent form's binding context. Next we determine which button fired the event. We typecast the sender object to a button type and then get the name property. The Select Case statement then takes over control. Instead of directly setting the row position, we use an intermediate variable to hold the results of a calculation that determines the new row. The new row is determined via an offset from the current row. If the new row would be beyond the last row, then we use the row index of the last row. If it would be negative or before the first row (row zero), then we use zero as the new row index.
Finally, we set the position using the parent form's binding context. We then call UpdatePosition to set the Text property and fire the PositionChanged event.