YourPaste - For your paste! Archive - Tools - Login

Binding Data Example

Posted by earlbob on Fri 3 Jul 2009 1:18 85 views - Syntax: VB.NET - Expires: never - Report - IMG - Download -

  1. ' Import Data and SqlClient namespaces...
  2. Imports System.Data
  3. Imports System.Data.SqlClient
  4.  
  5. Public Class Form1
  6.     ' Declare objects...
  7.     Dim objConnection As New SqlConnection _
  8.         ("server=myserver;database=pubs;user id=sa;password=mypassword")
  9.     Dim objDataAdapter As New SqlDataAdapter( _
  10.         "SELECT authors.au_id, au_lname, au_fname, " & _
  11.         "titles.title_id, title, price " & _
  12.         "FROM authors " & _
  13.         "JOIN titleauthor ON authors.au_id = titleauthor.au_id " & _
  14.         "JOIN titles ON titleauthor.title_id = titles.title_id " & _
  15.         "ORDER BY au_lname, au_fname", objConnection)
  16.     Dim objDataSet As DataSet
  17.     Dim objDataView As DataView
  18.     Dim objCurrencyManager As CurrencyManager
  19.     Private Sub FillDataSetAndView()
  20.         ' Initialize a new instance of the DataSet object...
  21.         objDataSet = New DataSet()
  22.  
  23.         ' Fill the DataSet object with data...
  24.         objDataAdapter.Fill(objDataSet, "authors")
  25.  
  26.         ' Set the DataView object to the DataSet object...
  27.         objDataView = New DataView(objDataSet.Tables("authors"))
  28.  
  29.         ' Set our CurrencyManager object to the DataView object...
  30.         objCurrencyManager = CType(Me.BindingContext(objDataView), CurrencyManager)
  31.     End Sub
  32.     Private Sub BindFields()
  33.         ' Clear any previous bindings...
  34.         txtLastName.DataBindings.Clear()
  35.         txtFirstName.DataBindings.Clear()
  36.         txtBookTitle.DataBindings.Clear()
  37.         txtPrice.DataBindings.Clear()
  38.  
  39.         ' Add new bindings to the DataView object...
  40.         txtLastName.DataBindings.Add("Text", objDataView, "au_lname")
  41.         txtFirstName.DataBindings.Add("Text", objDataView, "au_fname")
  42.         txtBookTitle.DataBindings.Add("Text", objDataView, "title")
  43.         txtPrice.DataBindings.Add("Text", objDataView, "price")
  44.  
  45.         ' Display a ready status...
  46.         ToolStripStatusLabel1.Text = "Ready"
  47.     End Sub
  48.     Private Sub ShowPosition()
  49.         'Always format the number in the txtPrice field to include cents
  50.         Try
  51.             txtPrice.Text = Format(CType(txtPrice.Text, Decimal), "##0.00")
  52.         Catch e As System.Exception
  53.             txtPrice.Text = "0"
  54.             txtPrice.Text = Format(CType(txtPrice.Text, Decimal), "##0.00")
  55.         End Try
  56.         ' Display the current position and the number of records
  57.         txtRecordPosition.Text = objCurrencyManager.Position + 1 & _
  58.         " of " & objCurrencyManager.Count()
  59.     End Sub
  60.  
  61.     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  62.         ' Add items to the combo box...
  63.         cboField.Items.Add("Last Name")
  64.         cboField.Items.Add("First Name")
  65.         cboField.Items.Add("Book Title")
  66.         cboField.Items.Add("Price")
  67.  
  68.         ' Make the first item selected...
  69.         cboField.SelectedIndex = 0
  70.  
  71.         ' Fill the DataSet and bind the fields...
  72.         FillDataSetAndView()
  73.         BindFields()
  74.  
  75.         ' Show the current record position...
  76.         ShowPosition()
  77.  
  78.     End Sub
  79.  
  80.     Private Sub btnMoveFirst_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMoveFirst.Click
  81.         ' Set the record position to the first record...
  82.         objCurrencyManager.Position = 0
  83.  
  84.         ' Show the current record position...
  85.         ShowPosition()
  86.  
  87.     End Sub
  88.  
  89.     Private Sub btnMovePrevious_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMovePrevious.Click
  90.         ' Move to the previous record...
  91.         objCurrencyManager.Position -= 1
  92.  
  93.         ' Show the current record position...
  94.         ShowPosition()
  95.  
  96.     End Sub
  97.  
  98.     Private Sub btnMoveNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMoveNext.Click
  99.         ' Move to the next record...
  100.         objCurrencyManager.Position += 1
  101.  
  102.         ' Show the current record position...
  103.         ShowPosition()
  104.  
  105.     End Sub
  106.  
  107.     Private Sub btnMoveLast_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMoveLast.Click
  108.         ' Set the record position to the last record...
  109.         objCurrencyManager.Position = objCurrencyManager.Count - 1
  110.  
  111.         ' Show the current record position...
  112.         ShowPosition()
  113.  
  114.     End Sub
  115.  
  116.     Private Sub btnPerformSort_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPerformSort.Click
  117.         ' Determine the appropriate item selected and set the
  118.         ' Sort property of the DataView object...
  119.         Select Case cboField.SelectedIndex
  120.             Case 0  'Last Name
  121.                 objDataView.Sort = "au_lname"
  122.             Case 1  'First Name
  123.                 objDataView.Sort = "au_fname"
  124.             Case 2  'Book Title
  125.                 objDataView.Sort = "title"
  126.             Case 3  'Price
  127.                 objDataView.Sort = "price"
  128.         End Select
  129.  
  130.         ' Call the click event for the MoveFirst button...
  131.         btnMoveFirst_Click(Nothing, Nothing)
  132.  
  133.         ' Display a message that the records have been sorted...
  134.         ToolStripStatusLabel1.Text = "Records Sorted"
  135.  
  136.     End Sub
  137.  
  138.     Private Sub btnPerformSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPerformSearch.Click
  139.         ' Declare local variables...
  140.         Dim intPosition As Integer
  141.  
  142.         ' Determine the appropriate item selected and set the
  143.         ' Sort property of the DataView object...
  144.         Select Case cboField.SelectedIndex
  145.             Case 0  'Last Name
  146.                 objDataView.Sort = "au_lname"
  147.             Case 1  'First Name
  148.                 objDataView.Sort = "au_fname"
  149.             Case 2  'Book Title
  150.                 objDataView.Sort = "title"
  151.             Case 3  'Price
  152.                 objDataView.Sort = "price"
  153.         End Select
  154.  
  155.         ' If the search field is not price then...
  156.         If cboField.SelectedIndex < 3 Then
  157.             ' Find the last name, first name, or title...
  158.             intPosition = objDataView.Find(txtSearchCriteria.Text)
  159.         Else
  160.             ' otherwise find the price...
  161.             intPosition = objDataView.Find(CType(txtSearchCriteria.Text, Decimal))
  162.         End If
  163.         If intPosition = -1 Then
  164.             ' Display a message that the record was not found...
  165.             ToolStripStatusLabel1.Text = "Record Not Found"
  166.         Else
  167.             ' Otherwise display a message that the record was
  168.             ' found and reposition the CurrencyManager to that
  169.             ' record...
  170.             ToolStripStatusLabel1.Text = "Record Found"
  171.             objCurrencyManager.Position = intPosition
  172.         End If
  173.  
  174.         ' Show the current record position...
  175.         ShowPosition()
  176.  
  177.     End Sub
  178.  
  179.     Private Sub btnNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNew.Click
  180.         ' Clear the book title and price fields...
  181.         txtBookTitle.Text = ""
  182.         txtPrice.Text = ""
  183.  
  184.     End Sub
  185.  
  186.     Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
  187.         ' Declare local variables and objects...
  188.         Dim intPosition As Integer, intMaxID As Integer
  189.         Dim strID As String
  190.         Dim objCommand As SqlCommand = New SqlCommand()
  191.  
  192.         ' Save the current record position...
  193.         intPosition = objCurrencyManager.Position
  194.         ' Create a new SqlCommand object...
  195.         Dim maxIdCommand As SqlCommand = New SqlCommand _
  196.            ("SELECT MAX(title_id) AS MaxID " & _
  197.             "FROM titles WHERE title_id LIKE 'DM%'", objConnection)
  198.  
  199.         ' Open the connection, execute the command
  200.         objConnection.Open()
  201.         Dim maxId As Object = maxIdCommand.ExecuteScalar()
  202.  
  203.         ' If the MaxID column is null...
  204.         If maxId Is DBNull.Value Then
  205.             ' Set a default value of 1000...
  206.             intMaxID = 1000
  207.         Else
  208.             ' otherwise set the strID variable to the value in MaxID...
  209.             strID = CType(maxId, String)
  210.             ' Get the integer part of the string...
  211.             intMaxID = CType(strID.Remove(0, 2), Integer)
  212.             ' Increment the value...
  213.             intMaxID += 1
  214.         End If
  215.  
  216.         ' Finally, set the new ID...
  217.         strID = "DM" & intMaxID.ToString
  218.  
  219.         ' Set the SqlCommand object properties...
  220.         objCommand.Connection = objConnection
  221.         objCommand.CommandText = "INSERT INTO titles " & _
  222.             "(title_id, title, type, price, pubdate) " & _
  223.             "VALUES(@title_id,@title,@type,@price,@pubdate);" & _
  224.             "INSERT INTO titleauthor (au_id, title_id) VALUES(@au_id,@title_id)"
  225.  
  226.         ' Add parameters for the placeholders in the SQL in the
  227.         ' CommandText property...
  228.  
  229.         ' Parameter for the title_id column...
  230.         objCommand.Parameters.AddWithValue("@title_id", strID)
  231.  
  232.         ' Parameter for the title column...
  233.         objCommand.Parameters.AddWithValue("@title", txtBookTitle.Text)
  234.  
  235.         ' Parameter for the type column
  236.         objCommand.Parameters.AddWithValue("@type", "Demo")
  237.         ' Parameter for the price column...
  238.         objCommand.Parameters.AddWithValue("@price", txtPrice.Text).DbType _
  239.                                       = DbType.Currency
  240.  
  241.         ' Parameter for the pubdate column
  242.         objCommand.Parameters.AddWithValue("@pubdate", Date.Now)
  243.  
  244.         ' Parameter for the au_id column...
  245.         objCommand.Parameters.AddWithValue _
  246.                       ("@au_id", BindingContext(objDataView).Current("au_id"))
  247.  
  248.         ' Execute the SqlCommand object to insert the new data...
  249.         Try
  250.             objCommand.ExecuteNonQuery()
  251.         Catch SqlExceptionErr As SqlException
  252.             MessageBox.Show(SqlExceptionErr.Message)
  253.         End Try
  254.  
  255.         ' Close the connection...
  256.         objConnection.Close()
  257.  
  258.         ' Fill the dataset and bind the fields...
  259.         FillDataSetAndView()
  260.         BindFields()
  261.  
  262.         ' Set the record position to the one that you saved...
  263.         objCurrencyManager.Position = intPosition
  264.  
  265.         ' Show the current record position...
  266.         ShowPosition()
  267.  
  268.         ' Display a message that the record was added...
  269.         ToolStripStatusLabel1.Text = "Record Added"
  270.  
  271.     End Sub
  272.  
  273.     Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
  274.         ' Declare local variables and objects...
  275.         Dim intPosition As Integer
  276.         Dim objCommand As SqlCommand = New SqlCommand()
  277.  
  278.         ' Save the current record position...
  279.         intPosition = objCurrencyManager.Position
  280.  
  281.         ' Set the SqlCommand object properties...
  282.         objCommand.Connection = objConnection
  283.         objCommand.CommandText = "UPDATE titles " & _
  284.                 "SET title = @title, price = @price WHERE title_id = @title_id"
  285.         objCommand.CommandType = CommandType.Text
  286.  
  287.         ' Add parameters for the placeholders in the SQL in the
  288.         ' CommandText property...
  289.  
  290.         ' Parameter for the title field...
  291.         objCommand.Parameters.AddWithValue("@title", txtBookTitle.Text)
  292.  
  293.         ' Parameter for the price field...
  294.         objCommand.Parameters.AddWithValue("@price", txtPrice.Text).DbType _
  295.                                       = DbType.Currency
  296.  
  297.         ' Parameter for the title_id field...
  298.         objCommand.Parameters.AddWithValue _
  299.                       ("@title_id", BindingContext(objDataView).Current("title_id"))
  300.  
  301.         ' Open the connection...
  302.         objConnection.Open()
  303.  
  304.         ' Execute the SqlCommand object to update the data...
  305.         objCommand.ExecuteNonQuery()
  306.  
  307.         ' Close the connection...
  308.         objConnection.Close()
  309.  
  310.         ' Fill the DataSet and bind the fields...
  311.         FillDataSetAndView()
  312.         BindFields()
  313.         ' Set the record position to the one that you saved...
  314.         objCurrencyManager.Position = intPosition
  315.  
  316.         ' Show the current record position...
  317.         ShowPosition()
  318.  
  319.         ' Display a message that the record was updated...
  320.         ToolStripStatusLabel1.Text = "Record Updated"
  321.  
  322.     End Sub
  323.  
  324.     Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
  325.         ' Declare local variables and objects...
  326.         Dim intPosition As Integer
  327.         Dim objCommand As SqlCommand = New SqlCommand()
  328.  
  329.         ' Save the current record position - 1 for the one to be
  330.         ' deleted...
  331.         intPosition = Me.BindingContext(objDataView).Position - 1
  332.  
  333.         ' If the position is less than 0 set it to 0...
  334.         If intPosition < 0 Then
  335.             intPosition = 0
  336.         End If
  337.  
  338.         ' Set the Command object properties...
  339.         objCommand.Connection = objConnection
  340.         objCommand.CommandText = "DELETE FROM titleauthor " & _
  341.                 "WHERE title_id = @title_id;" & _
  342.                 "DELETE FROM titles WHERE title_id = @title_id"
  343.  
  344.         ' Parameter for the title_id field...
  345.         objCommand.Parameters.AddWithValue _
  346.                       ("@title_id", BindingContext(objDataView).Current("title_id"))
  347.  
  348.         ' Open the database connection...
  349.         objConnection.Open()
  350.  
  351.         ' Execute the SqlCommand object to update the data...
  352.         objCommand.ExecuteNonQuery()
  353.  
  354.         ' Close the connection...
  355.         objConnection.Close()
  356.  
  357.         ' Fill the DataSet and bind the fields...
  358.         FillDataSetAndView()
  359.         BindFields()
  360.  
  361.         ' Set the record position to the one that you saved...
  362.         Me.BindingContext(objDataView).Position = intPosition
  363.  
  364.         ' Show the current record position...
  365.         ShowPosition()
  366.  
  367.         ' Display a message that the record was deleted...
  368.         ToolStripStatusLabel1.Text = "Record Deleted"
  369.  
  370.     End Sub
  371. End Class
  372.  

Comments


Name:
Comment:

© 2010 YourPaste.net - Disclaimer