Top Banner

of 12

VB4 DB Prac1-1

Mar 01, 2018

Download

Documents

Mogeni Jnr
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 7/25/2019 VB4 DB Prac1-1

    1/12

    3/20/20

    LAB

    WORKING WITH DATABASES I

    Using SQL Server DBs + Visual Studio

    Objectives

    To:

    Sort and filter database data &

    display data in a grid

    Using the DataGridView Control

    Selecting DataSet Rows

    2

    Objectives:To display rows and columns from a table

    Table SalesStaff, located in a database

    Company.

    Holds information collected about company sales

    employees.

    To allow users of your application to sort on

    any column, delete rows, and insert new

    rows.

    Lab 4-13

    The SalesStaff table

    The Table Design Sample Rows

    4

  • 7/25/2019 VB4 DB Prac1-1

    2/12

  • 7/25/2019 VB4 DB Prac1-1

    3/12

    3/20/20

    Lab 4-1

    Step 8: In the Add Connectionwindow, if the Data

    source entry does not say Microsoft SQL Server

    Database File, click the Changebutton and select that

    option.

    9

    Lab 4-1

    Step 9: Click the

    Browse button and

    locate the

    Company.mdf

    database you have

    been provided with.

    The figure shows an

    incomplete path to

    the Company.mdf

    filename because the

    actual path will be

    different on each

    computer.

    10

    Lab 4-1

    Step 10:Click the Test Connectionbutton. Assuming that the Test Connection

    succeededmessage displays, click the OK button two times to return to the

    wizard, and then click the Nextbutton.

    Step 11:You will see the following message asking you if you want to copy

    the database file to the project directory.

    By answering yes, you can easily move your program and its database to

    another computer. When you hand in programming projects, having the

    database stored with the project is a good idea. Click the Yesbutton to continue.

    11

    Lab 4-1

    Step 12:Now you are given the option of saving

    the connection string to the application configuration

    file (see figure below).

    Leave the option checked and click the Nextbutton

    to continue.

    12

  • 7/25/2019 VB4 DB Prac1-1

    4/12

    3/20/20

    Lab 4-1

    Step 13:Next, you are

    asked to select which

    database objects you

    want in your DataSet.

    Expand the entry

    under Tables, place a

    check next to SalesStaff,

    and change the

    DataSet name to

    SalesStaffDataSet (see

    figure).

    Click the Finish button

    to complete the

    wizard.

    13

    Lab 4-1

    Step 14: You should see column headings in the

    DataGridView control (see Figure below)

    that match the SalesStaff columns: ID, Last_Name,

    First_Name, Full_Time, Hire_Date, Salary.

    If the DataGridView Taskswindow is still visible, click

    anywhere outside the window to close it.

    14

    Lab 4-1

    Step 15:Next, you will center the Hire_Datecolumn.

    Refer to the figure in the next slide.

    Select the grids Columns property and open the Edit

    Columnswindow.

    Select the Hire_Datecolumn, and select DefaultCellStyle.

    This will display the CellStyle Builderwindow, shown in the

    figure.

    Select the Alignmentproperty, and select MiddleCenterfrom

    its dropdown list.Click the OKbuttons until theEdit Columnswindow is closed.

    15

    16

    1

    23

    4

  • 7/25/2019 VB4 DB Prac1-1

    5/12

    3/20/20

    Lab 4-1

    Step 16:Open the forms Codewindow, and inspect the

    code Visual Studio inserted into the forms Load event

    handler.Private Sub Form1_Load(sender As Object, e As EventArgs)Handles MyBase.Load

    'TODO: This line of code loads data into the

    'SalesStaffDataSet.SalesStaff' table. You can move, or remove

    it, as needed.

    Me.SalesStaffTableAdapter.Fill(Me.SalesStaffDataSet.SalesStaff)

    End Sub

    It calls the Fillmethod from the SalesStaffTableAdapter,

    passing it the SalesStaff DataTable inside the

    SalesStaffDataSet DataSet.

    17

    Lab 4-1

    Step 16 (cont):

    This is how the grid gets its data:

    The TableAdapterpulls data from the database, using

    theFillmethod.

    The Fillmethod holds an SQL query that determines

    which columns of which table will be used.

    The SalesStaff DataTable is a container that holds the

    data while it is being displayed by the DataGridView

    control.

    18

    Lab 4-1Showing the Salesstaff Table In A Datagridview Control

    Step 17:

    Save and

    run the

    application.

    You should

    see all the

    rows of the

    SalesStaff

    table, asshown in the

    figure.

    19

    Lab 4-1

    Step 18: Sorting

    Currently the rows are listed in ascending order by ID

    number.

    Click theLast_Namecolumn and watch the grid sort the rows

    inascendingorder by last name.

    Click the Last_Namecolumn again and watch the rows sort in

    descendingorder on the same column.

    Step 19: Column Widths

    Place the mouse over the border between two columns.When the mouse cursor changes to a horizontal arrow, use

    the mouse to drag the border to the right or left.

    This is how users can change column widths at runtime.

    20

  • 7/25/2019 VB4 DB Prac1-1

    6/12

    3/20/20

    Lab 4-1

    Step 20: Try deletinga row.

    Click the button to the left of one of the grid rows. The

    entire row is selected (highlighted).

    Press the Del keyand watch the row disappear.

    The row has been removed from the in-memory DataSet, but

    not the database.

    Step 21:Next, you will inserta new row.

    Scroll to the bottom row of the grid and enter

    the following information in the empty cells: 847, Jackson,

    Ochieng, (checkFull-time), 6/1/2011,65000.

    Press the Enterkey to save your changes.

    21

    Lab 4-1

    Step 22: Sort the grid on the Last_Name

    column, and look for the row you inserted.

    Step 23: Close the application and then run it

    again to verify thatthe changes you made to

    the DataSetwere not saved in the database.

    The grid rows look exactly as they did when you

    first displayed the DataSet.

    Stop the program again.

    22

    Lab 4-1

    Step 24: In Design view, notice the three components placed in

    the forms component tray by Visual Studio when you added

    the connection to theSalesStafftable.

    If you cant see them run the prog and lo ok at the forms design view.

    SalesStaffDataSet is the object that holds a copy of the

    database table in memory.

    SalesStaffBindingSource is the object that moves data from

    the dataset to the DataGridViewcontrol.

    SalesStaffTableAdapter is the object that copies data from

    the database into the dataset.As another option, it can save changes to the database.

    The TableAdaptercontains the SQL statements that select, update,

    insert, or delete database table rows.

    23

    Lab 4-1 Exercise

    Explain how to change the formatting of the Salary

    column so it displays values in currency format.

    24

  • 7/25/2019 VB4 DB Prac1-1

    7/12

    3/20/20

    Exercise AnswerFormatting GridView Columns

    To modify the columns in a

    DataGridView control, open the

    DataGridView Tasks window and select

    Edit Columnsfrom the popup menu.

    CellStyle Builder Window

    use it to select the column's alignment

    (TopLeft, MiddleRight, and so on), padding,

    format, foreground and background colors,

    font, and so on.

    25

    Exercise AnswerFormat Property

    (CellStyle Builder window)

    Format String dialog window:

    For general number formats, select Numeric and select

    the number of decimal places.

    For currency formats, select Currency and select the

    number of decimal places.

    For DateTime formats, select Date Time and select from

    a variety of format samples.

    For scientific formats, select Scientific and select the

    number of decimal places.

    26

    Selecting DataSet Rows27

    Selecting DataSet Rows

    Applications often must select (or filter) only certain

    rows for display e.g. for our db we want to display:

    only members of the company sales staff

    who are full-time or

    employees hired prior to 2005 or

    only those employees hired within the last five years

    whose salaries are less

    than $40,000.

    We filter rows using SQL queriesand the tools inVisual Studio.

    28

  • 7/25/2019 VB4 DB Prac1-1

    8/12

    3/20/20

    Selecting DataSet Rows

    Structured Query Language (SQL) is a

    standard language for working with

    databases.

    Although SQL is a language, you dont use it to

    write applications.

    It is intended only as a standard means of

    interacting with a database.

    You still need a general programming language

    such as Visual Basic to write applications with user

    interfaces.

    29

    Modifying the Query in a DataSource

    To edit a query used in a datasource, locate its DataSetschema file in the SolutionExplorerwindow.

    Since we created a data sourcenamed SalesStaffDataSet; thenthe DataSet schema file isnamedSalesStaffDataSet.xsd.

    Double-click the filename toopen the Dataset Designertool.

    By default, theSalesStaffTableAdapterhas onequery named Fill, GetData()that fills the DataSet when the

    form loads.

    30

    table name

    Dataset Designer tool

    The PK

    The TableAdapter query list

    DataSet Designer Window

    Contains TableAdaptersandDataTables

    Use it to view/modifyqueries

    right-click the DataSetand

    select Configurefrom thepopup menu,

    you can modify thecurrently selected query

    using the TableAdapterConfiguration Wizard (seefigure)

    31

    Query Builder

    If the query text is simple enough, you can modify it

    directly in this window.

    If the query is more complicated, click the Query

    Builderbutton to display a Query Builderwindow

    (see sample in figure).

    32

  • 7/25/2019 VB4 DB Prac1-1

    9/12

    3/20/20

    Query Builder

    Atool provided by Visual

    Studio for creating and

    modifyingSQL queries.

    Consists of four sections,

    calledpanes(see figure).

    To remove and restore

    panes, r ight-click the

    window and select Pane

    from the popup menu.

    The menu allows you to

    che ck o r u nche ck

    individual panes.

    To add a new tableto the

    Query Builder window,

    right-click inside the

    d iagram pane and

    select Add Tablefrom the

    popup menu.

    To save the current query

    and close Query Builder,

    click the OKbutton.

    33

    Thediagram panedisplays all the tables used in the

    query, with a check mark next to

    each field that will be used in the DataSet

    The grid pane displays the query in aspreadsheet-like format. You can choose a

    sort order and enter a selection criteria.

    The SQL pane displays the actual SQL query thatcorresponds to the tables and fields selected in the diagram

    and grid panes. You can write queries directly into this pane.

    Theresults pane displays the rows returned by executing the

    current SQL query. To fill the results pane, right-click in the

    QueryBuilder window and selectRunfrom the context menu.

    Query Builder

    For creating SQL queries

    Diagram pane

    add tables, show relationships, select columns

    Grid pane

    select columns, create aliases, set sort order, insert

    conditional expressions

    SQL pane

    directly edit the SQL server query's text

    Results pane

    show output when the query executes

    34

    Adding a Query to a Grid

    Use the TableAdapterobject in the component tray:

    In the form'sDesign view,

    right-click the TableAdaptericon and

    selectAdd Query

    theSearch Criteria Builderwindow appears

    35

    Adding a Query to a Grid

    You could modify the query so it reads as follows:SELECT ID, Last_Name, First_Name,

    Full_Time, Hire_Date, Salary FROMSalesStaff WHERE Salary < 45000

    You can give a name to the query, such as

    Salary_query.

    When you click the OKbutton, a ToolStripcontrol is

    added to the form, with a query button.

    When you run the application and click the

    Salary_query button on the ToolStrip, only rows with

    salaries less than $45,000 are displayed.

    36

  • 7/25/2019 VB4 DB Prac1-1

    10/12

    3/20/20

    Note

    1. If you dock a grid inside a form and then add a ToolStrip

    control, the grids title bar is covered up by the ToolStrip.

    To avoid this problem, set the grids Dockproperty to None, drag the

    grid a bit lower on the form with the mouse, and resize it so it fits.

    Then set the gridsAnchorproperty to Top, Bottom, Left, Right.

    2. If you add a query to a dataset and then later delete the

    query from the DataSet Designerwindow, your program may

    not run.

    If this happens, Visual Studio may have left behind some extra code

    that had been added to the designer file when the query was

    created.

    To sort this out, select the Rebuild command from

    Visual Studios Buildmenu.

    37

    ObjectiveTo create several queries that change the way rows

    from the SalesStaff table are displayed in a

    DataGridView control.

    Lab 4-2

    Filtering Rows in the SalesStaff Table38

    Lab 4-2

    Step 1:close Visual Studio to release its lock on the

    database file.

    Copy the SalesStaff 1folder you created in Lab 4-1 to a

    new folder named SalesStaff 2.

    Step 2:Open the project from the SalesStaff 2folder

    (the solution file will still be namedSalesStaff 1.sln).

    Step 3: Right-click the project name in the Solution

    Explorerwindow, and chooseRename.

    Rename the project SalesStaff 2.

    39

    Lab 4-2

    Step 4: In the Design window for Form1, right-click the

    SalesStaffTableAdaptercontrol in the component tray (or click

    the smart tag in the upper-right corner of the data grid) and

    selectAdd Queryfrom the popup menu.

    Step 5:In the Search Criteria Builderwindow, name the query

    Full_Time.

    Set its query text to the following:

    SELECT ID, Last_Name, First_Name,Full_Time, Hire_Date, Salary

    FROM dbo.SalesStaffWHERE (Full_Time = 'True')

    Step 6:Click the OKbutton to close the Search Criteria Builder.

    40

  • 7/25/2019 VB4 DB Prac1-1

    11/12

    3/20/20

    Lab 4-2

    Step 7: If your grid column headers are hidden

    behind the ToolStrip control, slide the grid downward

    to expose the column headers.

    Anchor it to the four sides of the form, using the

    Anchorproperty.

    Step 8:Save the project and run the application.

    Click the Full_Time buttonand observe that only full-time

    employees are displayed.

    Close the application and return to Design mode.

    41

    Lab 4-2

    Step 9: the source code generated by Visual Studio when the

    ToolStripButtonis added:

    A method named Full_Time, is called using the SalesStaffTableAdapter

    object.

    The argument passed to the method is the SalesStaff table inside the

    SalesStaffDataSetDataSet:

    Private Sub Full_TimeToolStripButton_Click() _Handles Full_TimeToolStripButton.Click

    TryMe.SalesStaffTable Adapter.Full_Time( Me.SalesStaffDataSet.Sal esStaff)

    Catch ex As System.ExceptionSystem.Windows.Forms.MessageBox.Show(ex.Message)

    End TryEnd Sub

    42

    Lab 4-2

    Step 10:Now you will add another button to the ToolStrip that

    displays all table rows.

    Right-click the SalesStaffTableAdapter control, or click the smart tag

    in the upper-right corner of the data grid and select Add Query.

    Step 11: In the Search Criteria Builder, name the query

    All_Rows, and keep the existing Query text.

    Click theOKbutton to close the window and create the query.

    Notice that a second ToolStrip has been added to the form, as

    shown in the following figure:

    43

    Lab 4-2

    Step 12: Again, you may need to adjust the

    top of the grid so the column headings are

    visible.

    Step 13:Save the project.

    Run the application and click both query buttons.

    The display should alternate between displaying

    all rows, and rows containing fulltime employees

    only. Step 14: End the application and close the

    project.

    44

  • 7/25/2019 VB4 DB Prac1-1

    12/12

    3/20/20

    Note

    It is possible to place both query buttons on the same ToolStrip.

    1. InDesignmode, select one of the buttons and cut it.

    2. Select the other toolbar and paste the button (press Ctrl-V).

    Both buttons should be on the same ToolStrip.

    3. Select and delete the empty ToolStrip.

    4. Open the Codewindow and observe that the Handles clause

    has disappeared from the Click event handler associated with

    the button you copied. Add the Handles clause back to the

    method header. For example:

    Handles All_RowsToolStripButton.Click

    45

    The Code So Far

    Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    'TODO: This line of code loads data into the 'SalesStaffDataSet.SalesStaff' table. You

    can move, or remove it, as needed.

    Me.SalesStaffTableAdapter.Fill(Me.SalesStaffDataSet.SalesStaff)

    End Sub

    Private Sub Full_timeToolStripButton_Click(sender As Object, e As EventArgs) Handles

    Full_timeToolStripButton.ClickTry

    Me.SalesStaffTableAdapter.Full_time(Me.SalesStaffDataSet.SalesStaff)Catch ex As System.Exception

    System.Windows.Forms.MessageBox.Show(ex.Message)

    End Try

    End Sub

    Private Sub All_RowsToolStripButton_Click(sender As Object, e As EventArgs) HandlesAll_RowsToolStripButton.Click

    Try

    Me.SalesStaffTableAdapter.All_Rows(Me.SalesStaffDataSet.SalesStaff)

    Catch ex As System.Exception

    System.Windows.Forms.MessageBox.Show(ex.Message)End Try

    End Sub

    End Class

    46

    Lab 4-2 Exercise

    Write a WHERE clause in SQL that limits the

    returned data to rows in which Salary is less than or

    equal to $25,000.

    47