Thursday, December 13, 2007

Binding Data to DataGrid Control (ASP.Net)

Bind the DataGrid control to the DataSet. This makes the control automatically display all of the data in rows and columns. The user can add, edit, and delete records using the DataGrid with no more work from you. You can use the DataGrid's properties if you want to restrict access. For example, you can make the DataGrid disallow editing.

Private Const SELECT_STRING As String = _
"SELECT * FROM Contacts ORDER BY LastName, FirstName"
Private Const CONNECT_STRING As String = _
"Data Source=Bender\NETSDK;Initial " & _
"Catalog=Contacts;User Id=sa"

' The DataSet that holds the data.
Private m_DataSet As DataSet

' Load the data.
Private Sub Form1_Load(ByVal sender As Object, ByVal e As _
System.EventArgs) Handles MyBase.Load
Dim data_adapter As SqlDataAdapter

' Create the SqlDataAdapter.
data_adapter = New SqlDataAdapter(SELECT_STRING, _
CONNECT_STRING)

' Map Table to Contacts.
data_adapter.TableMappings.Add("Table", "Contacts")

' Fill the DataSet.
m_DataSet = New DataSet()
data_adapter.Fill(m_DataSet)

' Bind the DataGrid control to the Contacts DataTable.
dgContacts.SetDataBinding(m_DataSet, "Contacts")
End Sub
Now use the SqlDataAdapter's Update method to update the database.

' Save any changes to the data.
Private Sub Form1_Closing(ByVal sender As Object, ByVal e _
As System.ComponentModel.CancelEventArgs) Handles _
MyBase.Closing
If m_DataSet.HasChanges() Then
Dim data_adapter As SqlDataAdapter
Dim command_builder As SqlCommandBuilder

' Create the DataAdapter.
data_adapter = New SqlDataAdapter(SELECT_STRING, _
CONNECT_STRING)

' Map Table to Contacts.
data_adapter.TableMappings.Add("Table", "Contacts")

' Make the CommandBuilder generate the
' insert, update, and delete commands.
command_builder = New _
SqlCommandBuilder(data_adapter)

' Uncomment this code to see the INSERT,
' UPDATE, and DELETE commands.
'Debug.WriteLine("*** INSERT ***")
'Debug.WriteLine(command_builder.GetInsertCommand.CommandText)
'Debug.WriteLine("*** UPDATE ***")
'Debug.WriteLine(command_builder.GetUpdateCommand.CommandText)
'Debug.WriteLine("*** DELETE ***")
'Debug.WriteLine(command_builder.GetDeleteCommand.CommandText)

' Save the changes.
data_adapter.Update(m_DataSet)
End If
End Sub

No comments: