How to: Navigate Data in Windows Forms
In a Windows application, the easiest way to navigate through records in a data source is to bind a BindingSource component to the data source and then bind controls to the BindingSource. You can then use the built-in navigation method on the BindingSource such a MoveNext, MoveLast, MovePrevious and MoveFirst. Using these methods will adjust the Position and Current properties of the BindingSource appropriately. You can also find an item and set it as the current item by setting the Position property.
Set the Position property of the BindingSource for your bound data to the record position to go to. The following example illustrates using the MoveNext method of the BindingSource to increment the Position property when the
nextButtonis clicked. The BindingSource is associated with the
Customerstable of a dataset
Setting the Position property to a value beyond the first or last record does not result in an error, as the .NET Framework will not allow you to set the position to a value outside the bounds of the list. If it is important in your application to know whether you have gone past the first or last record, include logic to test whether you will exceed the data element count.
Create an event handler for the PositionChanged event. In the handler, you can test whether the proposed position value has exceeded the actual data element count.
The following example illustrates how you can test whether you have reached the last data element. In the example, if you are at the last element, the Next button on the form is disabled.
Be aware that, should you change the list you are navigating in code, you should re-enable the Next button, so that users may browse the entire length of the new list. Additionally, be aware that the above PositionChanged event for the specific BindingSource you are working with needs to be associated with its event-handling method. The following is an example of a method for handling the PositionChanged event:
Find the record you wish to set as the current item. You can do this using the Find method of the BindingSource, if your data source implements IBindingList. Some examples of data sources that implement IBindingList are BindingList<T> and DataView.