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 acomponent 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 , , and . Using these methods will adjust the and properties of the BindingSource appropriately. You can also find an item and set it as the current item by setting the Position property.
To increment the position in a data source
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 nextButton is clicked. The BindingSource is associated with the Customers table of a dataset Northwind.
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.
To check whether you have passed the end or beginning
Create an event handler for theevent. 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:
To find an item and set it as the current item
Find the record you wish to set as the current item. You can do this using themethod of the BindingSource, if your data source implements . Some examples of data sources that implement IBindingList are and .