Using a DataGridView October 19, 2008
Posted by tuse in : ASP.NET, Databases, VB.NET , 4 commentsThe DataGridView Control Control can be used to display the contents of a table from the database as per an SQL query of user’s choice.
Let us see an example, add a DataGridView from the ToolBox to a new Windows Form.
When the Form Loads, we will look to fill the DGV with the following code-
Dim cmd As New Odbc.OdbcCommand("Select number as 'Book Number',title as 'Book Name', author as 'Author', publisher as 'Publisher', no_of_copies as 'No. of Copies', number_issued as 'No Issued', sub_category as 'Sub Category',edition as 'Edition' from book_details", cn)
'cn is the ODBC Connection Object defined in earlier posts
Dim adp As Odbc.OdbcDataAdapter
adp = New Odbc.OdbcDataAdapter(cmd)
Dim ds As New DataSet
adp.Fill(ds, "book_details")
Me.DataGridView1.DataSource = ds
Me.DataGridView1.DataMember = "book_details"
Me.DataGridView1.AutoResizeColumns()
We are using a DataSet-the core of the ADO.NET disconnected architecture and is used to store data in a disconnected state. In accordance to the SQL query, the DataSet is filled using the DataAdapter (adp).
The DataGridView comes with several options- enabling the user to edit records, add records, delete records.
In order to retrive data displayed in the DataGridView we can use the following code- this piece of code is very useful and I have used it on several occasions:
Dim i As Integer
i = DataGridView1.CurrentRow.Index
Dim book_number as Integer = DataGridView1.Item(0, i).Value
What we are doing in this piece of code is that we are are holding the current row’s index number in the variable i and thereafter the item in the first column in the variable book_number
