Drag the datagridview form to form and select a data source in the upper-right corner of the datagridview to bind data collections to a grid.
One of the most common and always Ally satisfying things to do with data binding is to have a set of data presented in a grid. most applications that deal with data need to present a collection of data in a grid so the user can see a summarized, compact view of that data. from there, the application may let users select individual rows and act upon them in some way. for now, we will just focus on the first step: taking a collection of data and presenting it in a tabular form to the user.
To present data in a tabular fashion, you need two things. first, you need the data that you want to present. the examples in this chapter use stronugly typed data sets from the northwinddataaccess class library created in Chapter 2. the other thing you need is a control capable of presenting the data in a tabular form. in Windows Forms 2.0, you useDatagridviewControl any time you want to present tabular data.
Let's take a quick look at the Code required to present a data table withinDatagridviewControl. The code in listing 3.2 is from a form's load event handler:
Listing 3.2. datagridview Data Binding
private void onformload (Object sender, eventargs e) {customersdataset nwdata = customersdataset. getcustomers (); m_customersgrid.datasource = nwdata. MERs ;} |
As you can see, you need to obtain the data set from your data access layer and setDatasourceProperty on the grid to the desired table within the data set. This example uses a strongly typed data set, so you just setDatasourceProperty on the grid to the table reference returned fromMERsProperty on the data set. This property returnsCustomersdatatableReference, which is simply a derived class fromDatatable(As discussed in chapter 2 ). all it takes is those two lines of codeand the code in the data access layer to create and populate the data setto have a rich presentation of data as shown in Figure 3.1. however, as you will see a little later in this chapter, you shoshould never bind your controls directly to a data source like this in.. NET 2.0; You shoshould bind your controls toBindingsourceComponent, and bind the binding source to the data source.
Figure 3.1. Presenting bound data in a form
[View full size image]