Data binding in Windows forms (i)

Source: Internet
Author: User
Tags bind contains connect query table name
window| data binding in Windows forms

Author: Liu Zhibo

Summary: This article explains how to use ado.net in Windows Forms to simply bind a form to data that contains any structure. Bind the control property of the form to the specified data through simple or complex data binding.
Goal:
Learn the basics of data binding in Microsoft.NET platforms
Learn how to generate a simple data binding form
Learn how to add ComboBox and ListBox to the data binding form you generate
learn to base Data-bound forms on the results of parameterized queries.
Learn how to bind data in a textbox
Premise:
Reading this article should look at the content:
Understanding the relational database and knowing how to access it
Knowledge of Structured Query language SQL
Access to a database service, such as SQL Server or access
Content:
Basic knowledge of data binding and Windows Form
Generate a simple data-bound Windows Form
Using ComboBox and ListBox
Data binding using a TextBox
Summarize
A. Basic knowledge of data binding and Windows Form
In general, data binding refers to the process of automatically setting the properties of one or more controls at run time to automatically obtain data from a structured data source. Windows forms uses ado.net to implement data binding. With data binding, you no longer need to write code to implement the connection (Connection) and generate Datasets (datasets), of course, in a form that does not bind data, the work is handwritten. Microsoft.NET's wizard will generate the necessary ado.net code for you without having to write your own handwriting.
Windows form allows you to easily bind to almost any structure that contains data. This means that you can help with any traditional data storage, such as data stored in Access or SQL Server tables, or data that is read from files, other controls that contain data, and data in an array. How the data is contained in the structure is not important to us in this article.
After you bind a form to data, you can bind the controls on the form to the specified data elements. Commonly used data binding involves binding the Text property of the textbox to a column in the data source. You can also help set the control's graphic properties, background-image properties, or any of the controls on the form.
Windows form includes two types of data binding: simple and complex. They have their own merits.
Simple bindings allow you to bind a control to a separate data element, which is often used to help set the value of a column in a table to a control on a form. In this way, it is commonly used on controls that display only a single value. A simple binding is typically a data bound to a TextBox or label.
Complex bindings allow you to bind multiple data elements, which are often used to set multiple columns or multiple Hong in a table to a control. Controls that support complex bindings are: DataGrid, ComboBox, ListBox.
B. Generating a simple data-bound Windows Form
. NET development environment, the most basic data binding purpose used is to display the contents of a table in a DataGrid. The following example illustrates several basic steps: (excluding details)
1. Generate a Windows Form
2. Generate and configure a dataset in form
3. Create a DataGrid in the form and bind him to the data
An example of using this step to form is shown in Figure 1

Figure 1. Results of generating a simple data binding form
Generate sample form
The following are detailed steps for creating the sample form:
1. Click File, click New, and then click Project. The New Project dialog box is then displayed.
2. Select Project Type in the tree row diagram to the left of the dialog box. For this example, select Visual Basic Projects.
3. Select Windows application in the list of templates to the right of the dialog box.
4. Fill in a name and select the path you want to save. Then click OK to generate this project.
5. Press F4 to display the property view of this form. Change the form's Name property to Frmcustomers.
6. Change the form's Text property to customer information.
Generating and configuring Datasets (Datasets)
Once you have created project and form, you can create and configure the dataset that is hidden under the form. A dataset is a cache of tables, relationships, and constraints stored in memory. Each table in the dataset contains a collection of row and column. Because the dataset records the original state and current state of the data, you can track any actions that you do on the data. The data in the dataset can be updated.
To create a dataadaper that contains SQL statements before data binding. Follow these steps to generate connection and dataadaper.
1. On the Toolbox data label, select Sqldataadaper and drag and drop him into the form. The data Adapter Configuration Wizard is then displayed. Then click Next.
2. Click New connection to generate a new data connection. The Data Link Properties dialog window, shown in Figure 2 below, is then displayed.

Figure 2. Use the Data Link Properties dialog box to specify connection information
3. Change server name to the name of the database you want to connect to. In our case, this is (local).
4. Change user Name, password to the necessary authentication information for connecting to the database.
5. Select the database used by the Northwind database as an example.
6. Click OK to return to Wizard, then click Next.
7. Wizard allows you to specify the query Type, as shown in Figure 3 below. Select Use SQL statements, then click Next.

Figure 3. Specify query type
8. Enter the SQL query statement or click Query Builder to generate the queries you need. In our example, enter the following query statement:
9. Select CustomerID, CompanyName, ContactName, ContactTitle, Country from Customers
10. Click Next, then click Finish to complete the process. Note that the wizard has generated two objects for you, SqlConnection1 and SqlDataAdatper1.
The SqlConnection1 object includes information about how to connect to the database. The SqlDataAdaper1 object includes query information that returns tables and columns from the database.
Note: Because our example uses a SQL Server database, SqlDataAdapter is used, and he only uses it to access the SQL Server database. If you are using OLE DB to connect to other types of databases, you should use OleDbDataAdapter.
Generate DataSet Object (DataSet)
The next is to generate a DataSet object that uses the DataAdapter query statement that was just generated. Follow the steps below to generate a dataset:
1. Click Data, then click Generate DataSet. The Generate DataSet dialog box, shown in Figure 4 below, is then displayed.

Figure 4. Generate DataSet dialog box specifies the object name and other properties
2. Enter Dscustomers as the name of the DataSet object to be generated. Note that you have selected the Add this dataset to the designer option. Click OK. This creates the dataset that is needed.
After this step is complete, you can see a new control dsCustomers1 in the Non-visual control area of form. This control is a reference to the file dscustomers.xsd and we can see this file in the Solution Explorer window. In this XSD file there is a class file that does not appear, and we can display this file by clicking Show All Files in the Project menu. You can then click the + number on the left side of the dscustomers.xsd file to see this class file Dscustomers.vb, as shown in Figure 5 below.

Figure 5. XML schema Definition (XSD) file has a class file to call the dataset into memory
Dscustomers.vb has attributes that correspond to the actual dataset and each column that corresponds to the specified in the query statement. Although we do not need to do anything with this class file, it is very useful to know its existence.
Add a DataGrid control to display data
You can now generate a form to display the data contained in the DataSet. In this example, add a separate DataGrid control to the form. This datagrid is used to display the data contained in the DataSet. Start with the following steps:
1. At the top of the window, click on the tab to display the Frmcustomers form.
2. Click the Toolbox tab of Windows Forms to drag a DataGrid control to the form. Adjusts the Size property of the DataGrid to an appropriate size.
3. Press F4 to display the Properties window for this DataGrid.
4. Select the value of the DataSource property is DsCustomers1
5. Select the value of the DataMember property is customers
These steps are done to bind a DataGrid to a dataset. In order to see the data displayed, the following steps are required.
Fill data into the DataGrid control
Although the DataGrid control is already bound to a dataset, the dataset does not automatically export the data to the DataGrid when the form is transferred. We use the form's Load event to populate the DataGrid data when the from is being transferred.
Private Sub Frmcustomers_load (_
ByVal sender as System.Object, _
ByVal e as System.EventArgs) Handles MyBase.Load
' Load the ' Data Grid control
Dscustomers1.clear ()
SqlDataAdapter1.Fill (DsCustomers1, "Customers")
End Sub
In the Load event, first clears the data in the dsCustomers1 (clear), and then populates the data in the dsCustomers1 with the SqlDataAdapter1 fill method. Here, to fill in the second parameter for the table name, this table name is used for the DataMember property of the DataGrid we specified earlier.
Run
You can now see the data in the Customers table displayed in the DataGrid. We have a job to do before we run. Because we changed the Name property of the form, tell project which form to start.
1. In the Solution Explorer window, click on the project name.
2. Right-click and select Properties from the shortcut menu
3. Click Startup Object, and then select Frmcustomers from the list.
4. Click OK
5. Press F5 to run the program. If you do the right thing, you can see the data in the Customer table in the DataGrid shown in Figure 1.
C. Use of ComboBox and ListBox
The example is suitable for small datasets, which is not appropriate if you have thousands of data in a customer table. The problem is that it reads all the customer data and displays it on the DataGrid. As an example, it is no longer appropriate to use it as a product program.
The database server is optimized for reading large amounts of data, but we should read only small datasets. It would be more effective if we added a ComboBox to the previous example to select the country and show only the customers in the country. In this section, we do it. The next section shows how to use ComboBox to limit the data displayed in the DataGrid. We follow the following steps:
1. Add a second DataAdapter to the form
2. Generate a second dataset
3. Add a ComboBox to the form
4. Bind the ComboBox to the dataset you just generated
5. Obtain the data to be displayed in the ComboBox from the DataAdapter
Add a second DataAdapter to the form
Before using ComboBox, add a DataAdapter first. and use this DataAdapter to generate DataSet data that contains a list of countries with no duplicates. Add DataAdapter Follow these steps:
1. In the Toolbox data label, select SqlDataAdapter, drag and drop into the form. The DataAdapter Configuration Wizard dialog box is then displayed. Click Next.
2. Select the connection to the Northwind database. Click Next
3. Choose Use SQL statements, click Next
4. Enter the following SQL statement:
Select distinct Country from Customers
5. Click on the Advanced Options button on the dialog box
6. Clear the Generate Insert, Update, and Delete statements option as shown in Figure 6 below. These statements are not available when we use ComboBox to display the country. Click OK to close the dialog box.

Figure 6. Do not select Generate Insert, Update and Delete statement option
7. Click Finish to generate DataAdapter
Now in form there is an object named SqlDataAdapter2.
Generate a second dataset
The dataset class and XSD file for this new DataAdapter are then generated. Follow these steps as follows:
1. Click Data and then shock the generate DataSet. The Generate DataSet dialog box is displayed.
2. Ensure that the customers (SQLDATAADAPTER2) in the list box is selected
3. Click New, and then enter the name Dscountries. Ensure that the add this DataSet to the designer option is selected. Click OK. The dataset is generated.
In this way, a new object dscountries and a new XSD file dscountries.xds are added. These two items generate a dataset class and are then used in ComboBox data binding.
Add ComboBox
Now you can add ComboBox, adjust the size of the form and the size of the DataGrid to show the ComboBox. You can then drag a ComboBox from the Toolbox into the form and put him on top of the DataGrid, as shown in Figure 7 below:

Figure 7. A form containing ComboBox and a DataGrid
Bind the ComboBox to the DataAdapter.
The combobox you just added is not yet bound to any data. Follow the steps below to bind him to the dscountries:
1. Choose this ComboBox
2. Change the Name property to Cbocountry
3. Set the DataSource property to DsCountries1. This specifies his data source.
4. Change the DropDownStyle property to DropDownList.
5. Set the DisplayMember property to Customers.country. Click the Drop-down list for the DisplayMember property, and then expand customers to display the columns you can use. This step specifies the columns to display.
6. Set the ValueMember property to Customers.country. The ValueMember property is used when the item is selected, the value that is actually used.
Export Data to ComboBox
As with the DataGrid, we have to write some code to export the data to ComboBox. In the form's Load event we add the following code after the original code:
Private Sub Frmcustomers_load (_
ByVal sender as System.Object, _
ByVal e as System.EventArgs) Handles MyBase.Load
' Load the ' data grid control
Dscustomers1.clear ()
SqlDataAdapter1.Fill (DsCustomers1, "Customers")
' Load the Combo Box
Dscountries1.clear ()
Sqldataadapter2.fill (DsCountries1, "Customers")
End Sub
The code shown in bold is the code we want to add. It looks almost the same as the code that displays the DataGrid data.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.