Introduction to Microsoft VB.NET

Introduction to Microsoft VB .NET SEG3510 Tutorial 1 (Jan 17) 2007 Spring Semester Prepared by Kelvin Chan ([email protected]) Special thanks to ...
Author: Branden Benson
1 downloads 0 Views 231KB Size
Introduction to Microsoft VB .NET

SEG3510 Tutorial 1 (Jan 17) 2007 Spring Semester Prepared by Kelvin Chan ([email protected]) Special thanks to Cheryl Wong for providing previous notes for reference

Introduction to VB.NET • VB = Visual Basic • .NET = Microsoft .NET Framework – Requires the .NET framework to execute

• Uses the Visual Studio .NET IDE (Integrated Development Environment) • Features – A very high level language – Easy to implement your program(Esp. GUI) – Object oriented

First Application – Hello World • Launch Visual Studio .NET: Start → Programs → Microsoft Visual Studio .NET → Microsoft Visual Studio .NET • Create new application: File → New → Project • Select project type as Visual Basic Project and template Windows Application • Try it youself: Create a new Visual Basic Windows Application called HelloWorld

First Application – Hello World

Solution Explorer Design View Properties Window

First Application – Hello World Server Explorer Toolbox

Switch code/ design mode

First Application – Hello World • Design your interface – Adding controls to your Form by drag-and-drop from the Toolbox – Configure Form Properties

• Lab: – – – –

Change the header text of Form1 to “Hello World” Add a button with name “btnHello” and text “Hello” Add a button with name “btnNext” and text “Next” Add a textbox named “txtHelloBox” remove the text initially – Resize and properly place the form, buttons and text boxes

First Application – Hello World

Good Naming Convention • Precede the variable name by the abbreviation of component type • Variables: use the Hungarian Notation – e.g. bBoolean, iInteger, dwDoubleWord – Reference • http://en.wikipedia.org/wiki/Hungarian_notation • http://msdn2.microsoft.com/enus/library/ms229045.aspx

First Application – Hello World • Add a new form: Project → Add Windows Form • or Solution Explorer → Right Click solution name → Add New Item → Windows Form • Try it yourself: – Add a new Windows Form called “frmNewForm” and titled “New Form” – On “Next Form”, add a label with text “Hello World Page 2” and button “Exit” – Name the components properly!

First Application – Hello World

First Application – Hello World • Events: an action to which the application can respond (e.g. mouse clicking, pressing a key) • Write your own code to handle the event • Most objects handle the click event • In VB, double click the button on the form to define the actions for click event

First Application – Hello World • Now it comes the time to write your code • Double click the “Hello” button in the first form and the code mode will pop out

First Application – Hello World • Add the code: Private Sub btnHello_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHello.Click txtHelloBox.Text = "Hello World!”

End Sub

• Similarly, double-click the “Next” Button and add the code: Private Sub btnNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHello.Click Me.Hide() Dim form2 As New frmNewForm form2.ShowDialog() form2.Close() End Sub

First Application – Hello World • Try to add the code for the “Exit” button in frmNewForm • Hint: the code for program exit is Application.Exit() • To compile and run the program, press the Debug button

First Application – Hello World • Try whether all the features work

Notes about VB programming • Punctuation – VB does not use braces {}, semicolons ; – Properly indent (the IDE helps you to do this) – Subroutines end with a pair of brackets (), through which parameters (if any) are passed – Comments start with a single quote ‘ – Not case sensitive, but it is a good practice to use consistent case

Notes about VB programming • Variables – Declaration and initialization. The general form for general a variable is: • Dim variable_name As data_type

– Here are some examples of declaration. – ‘creates an Integer variable named x. • Dim x As Integer • ‘multiple variables declaration. • Dim x As Integer, i,j As Long, s As String • ‘declares an Integer variable and initializes it to 3. • Dim x As Integer = 3

Notes about VB programming • Variables – Variable scope • If a variable is defined inside a code block, then the variable has block-level scope. (i.e. It is only visible within that block.) Dim x As Integer = 10 Sub Test() If x > 1 Then ‘local variable rec cannot be recognized outside ‘the block in which it is defined. The block from ‘If … End If Dim rec As Integer rec = 1 / x End If MsgBox(CStr(rec)) ‘Error! End Sub

Notes about VB programming •

Array declaration – Dim array_name(x) As array_type – The number x is the upper bound of the array. Thus, the array elements are array_name(0) through array_name(x), and the array has x+1 elements. – There are different declaration notation and their corresponding meaning ‘implicit constructor: no initial size and no initialization Dim Days() As Integer ‘explicit constructor: no initial size and no initialization Dim Days() As Integer = New Integer() {} ‘Implicit constructor: Initial size but no initialization Dim Days(6) As Integer ‘explicit constructor: initial size but no initialization Dim Days( ) As Integer = New Integer(6) {} ‘implicit constructor: initial size implied by Initialization Dim Days( ) As Integer = {1, 2, 3, 4, 5, 6, 7} ‘explicit constructor: initial size and initialization Dim Days( ) As Integer = New Integer(3) {1, 2, 3}

Notes about VB programming •

Subroutines – Subroutine is like a function or operator of a class. Following is a sample subroutine: ‘declare a subroutine Private Sub NewSubRoutine (ByVal a As Integer) Handles Button1.Click ‘write your own subroutine code End Sub

– You can call the subroutine by: • NewSubRoutine(x) ‘x is an integer variable

Notes about VB programming • Subroutines – There are explanations of the sample subroutine. • Private: Only the code within that module / object can see and use the subroutine. • Public: Anywhere can see and use the subroutine. Both can be added in subroutines, variables and objects. • ByVal: Default value. It means that this parameter is being passed by value. The function changing the values of that parameter will not effect the original variable changes. • ByRef: It means that the original variable is passed by reference. The original variable is changed if the function changes the parameter. (In C language: similar to pass by pointer) • Sub, End Sub: The keyword for starting a subroutine and ending the subroutine. • Handles: The keyword means that the subroutine will be invoked if the given event happens. In the sample code, NewSubRoutine will be called when the user clicks Button1.

Connect to Access Database • Create new Access file: – Start Microsoft Access. – File → New → Blank Database → Create table in Design View

Connect to Access Database • Create a new Access file (Cont’d) – Type in the attribute names and choose the attribute types for your database – You may define a primary key (optional) – Fill-in your data by double clicking the created tables

• Try it yourself: create a new access database called “student.mdb” with attribute Name, Dept and Grade, fill-in 3 to 5 lines of data

Connect to Access Database

Connect to Access Database • In VB.NET applications – Tools → Connect to Database – On Provider tab, select Microsoft Jet 4.0 OLE DB Provider → Next – Select or type in your Access file → Test (Reminder: errors pop up if you did not fill in the table in Access properly) – Click OK and go to Advance tab – Modify Access permissions when necessary – Expand your connection in Server Explorer to view the list of database tables

Connect to Access Database •

Drag the table onto the Form, you will notice 2 widgets on the bottom, rename them on the Properties windows

Connect to Access Database • •

Select your Form, and then go to Data → Generate Dataset Select the table with checked the corresponding checkbox. Check the Add this dataset to the designer.



Click OK. You will notice that an .sxd template schema has been added to the Solution Explorer

Connect to Access Database • A new icon is added at the bottom. Rename the dataset when necessary. • You may use DataBindings to bind database content to user controls.

Connect to Access Database •

Retrieve information from database: – Tell the DataAdapter to pour information from the database straight into our Dataset • DataAdapter_name.Fill(DataSet_name) – Move to the next record • BindingContext(DataSet_name, "table_name").Position += 1 – Move to the previous record: • BindingContext(DataSet_name, " table_name ").Position -= 1 – Add new record • BindingContext(DataSet_name, " table_name ").AddNew() • DataAdapter_name.Update(DataSet_name) – Remove a record • BindingContext(DataSet_name, "table_name").RemoveAt(IndexNumber) – Find out the IndexNumber of the current record: • IndexNumber = BindingContext(DataSet_name, "table_name").Position

Connect to Access Database •

Please use relative path as showing the following example: – Dim objConnection as New OleDb.OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = “ + CurDir() + “\student.mdb")

• • •

If you do not use code completely, go to Edit -> Find and Replace -> Find in Files and then search your database name (e.g. db1.mdb). You can find something like following, – Me.OleDbConnection1.ConnectionString = "Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Registry Path=;Jet OLEDB:Database Locking Mode=1;Data Source=" “c:\seg3510\student.mdb" ";…



Replace the bold parts to – + CurDir() + “\student.mdb”+



Otherwise, portability is not guaranteed and marks will be deducted.

Connect to XML • A sample XML file Mary Cheung SEM CSC John Wong IEE

Connect to XML • In .NET framework: use xmlTextReader to read XML • Open XML for reading from file: – Dim MyReader As New Xml.XmlTextReader("file_path")

• Read a block: – MyReader.Read()

• Find the node type (Xml.XmlNodeType.Element, Xml.XmlNodeType.Text, Xml.XmlNodeType.EndElement, etc.): – MyReader.NodeType()

Connect to XML • •



Whether the tag has attribute(s): – MyReader.HasAttributes() ‘Return true or false Number of attribute(s): – ‘Return Integer Attribute value – ‘(MyReader is holding the attribute): – MyReader.AttributeCount() – MyReader.Value() ‘Return the attribute value Element / attribute’s name: – MyReader.Name() ‘Return attribute name

References • •

SEG3510 FAQ page Microsoft Student DevClub (CUHK) – http://stdclub.se.cuhk.edu.hk/forums/



Code Samples from MSDN – http://msdn.microsoft.com/vbasic/downloads/samples/default.aspx



Developing Microsoft .NET Applications on VB.NET – http://www.msdnaa.net/curriculum/pfv.aspx?5488



devCity.NET – http://www.devcity.net/net/



CodeHound VB - The Visual Basic Developer's Search Engine – http://www.codehound.com/vb/



The Code Project – http://www.codeproject.com/vb/net/



Microsoft Visual Studio .NET Documentation – Start Menu: Start → Programs → Microsoft Visual Studio .NET → Microsoft Visual Studio .NET Documentation



Suggest Documents