' ---------------------------------
' Code by Chris Andersen(AKA Cander)
' This example shows how to show data from an access database in the DataGrid control
' and how to write a new record to the database.
' ---------------------------------
' Using Code Behind, we can fully seperate presentation from code.
Imports System
Imports System.Data
Imports System.Data.OleDb
Imports System.Web.UI
Imports System.Web.UI.WebControls
Public Class Cander1
' Declare the class and have it inherit the System.Web.UI.Page class. This is needed for
' accessing the ASP.NET Page's Events/Properties/Methods
Inherits Page
' We need to declare all web controls we use. Since the aspx page will inherit this class, they
' must be Public in order to be visible.
Public lblName As Label
Public lblAge As Label
Public MyDataGrid As DataGrid
Public tbName As TextBox
Public tbAge As TextBox
Public btnAdd As Button
Public btnView As Button
Dim myDS As New DataSet
Dim myConn As OleDbConnection
Dim myCommand As OleDbDataAdapter
Dim strConnString As String = "Provider=Microsoft.Jet.OLEDB.4.0;data source=" & Server.Mappath("/candersen/db/test.mdb")
Dim strSQL As String
Sub Page_Load(Sender As Object, E As EventArgs)
' This sub is called everytime the Page Loads
End Sub
Sub Add_Click(Sender As Object, E As EventArgs)
Dim strName As String = Name.Text
Dim strAge As String = Age.Text
' Write posted data to the lables
lblName.Text = strName
lblAge.Text = strAge
' Insert Posted Data to database
strSQL = "Insert Into Test(Name,Age) VALUES('" & strName & "','" & strAge & "')"
' Populate DataSet
FillDataSet()
' Update DataGrid
UpdateGrid()
End Sub
Sub UpdateGrid()
' Updates the DataGrid
strSQL = "Select * FROM Test"
'Populate DataSet
FillDataSet()
' Now set the DataGrid's source to the Dataset and bind it
MyDataGrid.DataSource = myDS.Tables("Test").DefaultView
MyDataGrid.DataBind()
End Sub
Sub FillDataSet()
' Recordset no longer exists for ADO.NET. Create DataSets and populate it from the data you get from
' a DataAdapter or other source(like XML). In this case we are getting ADO DataSet using the System.Data.OleDb.OleDbDataAdapter
' Start Connection to ADO source
myConn = New OleDbConnection (strConnString)
' Run the Sql statement and get the Data into the DataAdapter
myCommand = New OleDbDataAdapter(strSQL, myConn)
' Fill the DataSet and name the table
myCommand.Fill(myDS, "Test")
myConn.Close()
End Sub
End Class