WinForm 2.0 无代码DataGridView绑定
拖动datagridview到form上,点击datagridview的右上方选择数据源进行绑定即可
Binding Data Collections to a Grid
One of the most common and visually 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 strongly 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 use the DataGridView control any time you want to present tabular data.
Let's take a quick look at the code required to present a data table within the DataGridView control. 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.Customers; } |
As you can see, you need to obtain the data set from your data access layer and set the DataSource property on the grid to the desired table within the data set. This example uses a strongly typed data set, so you just set the DataSource property on the grid to the table reference returned from the Customers property on the data set. This property returns a CustomersDataTable reference, which is simply a derived class from DataTable (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 should never bind your controls directly to a data source like this in .NET 2.0; you should bind your controls to a BindingSource component, and bind the binding source to the data source.
Figure 3.1. Presenting Bound Data in a Form