DataGridViewControls are highly configurable and scalable. It provides a large number of attributes, methods, and events that can be used to customize the appearance and behavior of the control. The following example shows how to add, delete, modify, and query a DataGridView datagriand synchronize it to a database.
Form display:
User Requirements:
1. When the form is displayed, the data in the User table in the database is displayed.
2. Select a row and perform the delete operation. The corresponding data in the database is also deleted.
3. Double-click a data item to edit it, or add new data in a blank row, and click Update. The database is updated accordingly.
Code display:
The Public Class Form1 code is relatively simple and does not use a three-tier architecture. Public DT As DataTable Public SDA As SqlDataAdapter Private Sub Form1_Load (sender As Object, e As EventArgs) Handles MyBase. load Dim conn = New SqlConnection ("Server = ***; DataBase = userinfo; User ID = ***; Password = ***") SDA = New SqlDataAdapter ("select * from Users", conn) DT = New DataTable SDA. fill (DT) 'transmits the Retrieved Data to DataGridView1.DataSource = DT' in the able, and transmits the data in the able to DataGridView1 to display the End Sub 'Update operation Private Sub btnUpdate_Click (sender As Object, e As EventArgs) handles btnUpdate. click Dim SCB = New SqlCommandBuilder (SDA) SDA. update (DT) MsgBox ("updated successfully") End Sub 'delete the Private Sub btnDel_Click (sender As Object, e As EventArgs) Handles btnDel. click 'delete the selected row maid. removeAt (maid. rowIndex) 'delete Dim SCB = New SqlCommandBuilder (SDA) SDA in the database. update (DT) MsgBox ("deleted successfully") End SubEnd Class
Note:
1. The corresponding table in the database must have a primary key.
2. Enable the edit and delete functions of the DataGridView.
Code parsing:
1. DataSet and DataTable:
DataSet: a DataSet. It is a temporary database that stores data from the data source in the memory and is independent of any database. It generally contains multiple able and constraints between DataTable. You can use dataset ["table name"] to obtain the DataTable.
2. SqlDataAdapter:SqlDataAdapter object name = new SqlDataAdapter (query using SQL statements, database connection );
The Fill method fills data in the data table. The Update method submits the data in the data table to the database.
3. SqlCommandBuilder object:
SqlCommandBuilder builder = new SqlCommandBuilder (the created DataAdapter object );
The SqlCommandBuilder object can be used to automatically generate the INSERT, UPDATE, and DELETE commands.
The above is only the tip of the iceberg, and the functions of the DataGridView are particularly powerful. There is no end to learning!