The DataGridView control is highly configurable and extensible. It provides a number of properties, methods, and events that you can use to customize the appearance and behavior of the control. The following is a small example to show the DataGridView for the function of adding and checking, and synchronizing to the 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 to perform the delete operation while the corresponding data in the database is deleted.
3. Double-click on a data, edit it, or add new data to a blank line, then click Update and the database is updated.
Code Show:
The public Class Form1 ' code is simpler 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=***;D atabase=userinfo; User id=***; password=*** ") SDA = new SqlDataAdapter (" select * from Users ", conn) DT = new DataTable SDA. Fill (DT) ' passes the data to the DataTable Datagridview1.datasource = DT ' passes data from DataTable to DataGridView1 show End Sub ' update operation Private Sub Btnupdate_click (sender as Object, e as EventArgs) Handles btnupdate.click Dim SCB = New sqlcommandbuild ER (SDA) SDA. Update (DT) MsgBox ("Update succeeded") End Sub ' delete operation Private Sub Btndel_click (sender as Object, e as EventArgs) Handles Btndel.click ' Delete selected rows DataGridView1.Rows.RemoveAt (DataGridView1.CurrentCell.RowIndex) ' Database for deletion Dim SCB = New SqlCommandBuilder (SDA) SDA. Update (DT) MsgBox ("Delete succeeded") End SubEnd Class
Attention:
1. There must be a primary key in the corresponding table in the database.
2.DataGridView Enable the Edit and delete feature.
Code parsing:
1.DataSet and DataTable:
DataSet: A dataset that is simply understood as a temporary database that stores data from a data source in memory, independent of any database. Typically contains multiple DataTable, and a constraint relationship between the DataTable. Get a DataTable by dataset["table name"].
2.SqlDataAdapter: SqlDataAdapter object name = NewSqlDataAdapter (Query withSQLStatement,Database Connection);
The Fill method populates the data table with data. The Update method submits the data in the data table to the database.
3.SqlCommandBuilder objects:
SqlCommandBuilder builder =new SqlCommandBuilder (created DataAdapter object);
Use the SqlCommandBuilder object to automatically generate: Insert command, update command, delete command.
The above show is just the tip of the iceberg, DataGridView features particularly powerful. Learning!