Faculté d’Ingénieurs en Informatique, Multimédia,
Systèmes, Télécommunication et Réseaux
Master en Génie Logiciel
et
Préparé par Elie MATTA
Copyright © 2010-2011, . All rights reserved
Cours, Exemples et Exercices de la matière et
Préparé par Elie Matta
Exemples:
1. Using ListBox:
Option Strict Off
Public Class Form1
Sub incrementer()
Static number As Integer = 0 'si on met Dim on aura comme resultat 0'
Console.WriteLine(number)
number += 1
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Dim V() As Integer
V = New Integer(5) {0, 1, 2, 3, 4, 5}
ReDim Preserve V(7)
V(6) = 6
V(7) = 7
Dim c(,) As Integer = {{1, 2}, {3, 4}}
For i As Integer = 0 To 5
(V(i).ToString)
Next i
For i As Integer = 0 To 7
(V(i).ToString)
Next i
For i As Integer = 0 To 1
For j As Integer = 0 To 1
(c(i, j).ToString)
'ou '
Next j
Next i
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button3.Click
For i As Integer = 1 To 5
incrementer()
Next i
End Sub
End Class
Copyright © 2010-2011, . All rights reserved Page 2
Cours, Exemples et Exercices de la matière et
Préparé par Elie Matta
2. Using Modules and creating classes:
In Form1:
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles
End Sub
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles TextBox1.TextChanged
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Dim add As Customer.FullAddress
Dim cust As Customer
cust = New Customer()
add = New Customer.FullAddress()
add.street =
=
cust.address = add
End Sub
Private Sub TextBox2_TextChanged(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles TextBox2.TextChanged
End Sub
End Class
In Module1:
Module Module1
Public Class Customer
Class FullAddress
Public street As String
End Class
Public name As String
Public address As FullAddress
End Class
End Module
Copyright © 2010-2011, . All rights reserved Page 3
Cours, Exemples et Exercices de la matière et
Préparé par Elie Matta
3. Adding Values of a table using InputBox:
Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Dim V(4) As Integer
For i As Integer = 0 To V.Length - 1
V(i) = CInt(InputBox("Entrer votre valeur", "Test"))
Next
(add(V))
End Sub
Public Function add(ByVal ParamArray V() As Integer) As Integer
Dim R As Integer = 0
For i As Integer = 0 To V.Length - 1
R += V(i)
Next
Return R
End Function
4. Get and Set:
Class class1
Private _Poids As Integer
Public Property poids() As Integer
Get
Return _Poids
End Get
Set(ByVal value As Integer)
If (Value < 20 Or Value > 90) Then
("Pas admise")
Else
_Poids = value
("Admise")
End If
End Set
End Property
End Class
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Dim c As New class1
Dim a As String
a =
c.poids = a
End Sub
End Class
Copyright © 2010-2011, . All rights reserved Page 4
Cours, Exemples et Exercices de la matière et
Préparé par Elie Matta
5. Creating namespace:
We should put Imports before public class Form1
Imports ns1 = WindowsApplication1.topwa
Namespace top
Public Class inside
End Class
Public Class sameclass
End Class
End Namespace
Namespace topwa
Public Class inside
End Class
Public Class sameclass
End Class
End Namespace
In the button
Dim cls1 As New top.inside() 'using namespace without alias
Dim cls2 As New top.sameclass()
Dim cls3 As New ns1.inside()'using namespace with alias
Dim cls4 As New ns1.sameclass()
6. Example with Delegate
Imports ns1 = WindowsApplication1.topwa
Namespace topwa
Public Class inside
Public Sub s1(ByVal x As Int16)
("S1:" & x)
End Sub
Public Sub s2(ByVal y As Int16)
("S2:" & y)
End Sub
Public Sub s3(ByVal z As Int16)
("S3:" & z)
End Sub
End Class
End Namespace
In the button :
Dim x, y, z As String
Dim s1, s2, s3 As dl
x =
y =
z =
Dim cls As New ns1.inside()
Copyright © 2010-2011, . All rights reserved Page 5
Cours, Exemples et Exercices de la matière et
Préparé par Elie Matta
s1 = New dl(AddressOf cls.s1)
's1(x)
s2 = New dl(AddressOf cls.s2)
's2(y)
s3 = [Delegate].Combine(s1, s2)
s3(z)
In the Form:
Delegate Sub dl(ByVal x As Int16)
Copyright © 2010-2011, . All rights reserved Page 6
Cours, Exemples et Exercices de la matière et
Préparé par Elie Matta
Exercices:
Exercice 1:
En utilisant la commande InputBox saisr une valeur i de type integer et puis effectue les test
suivant :
? i? 0<= i <= 10
? 11<= i <= 20
? i>20
En utilisant une structure if et une structure select case.
Affiche pour chaque cas un message indiquant le resultat
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Dim a As Integer
a = InputBox("Test value", "Using select case")
Select Case a
Case Is < 0
("a<0")
Case Is <= 10
("a between 0 and 10")
Case Is <= 20
("a between 11 and 20")
Case Is > 20
("a plus grand que 20")
End Select
Copyright © 2010-2011, . All rights reserved Page 7
Cours, Exemples et Exercices de la matière et
Préparé par Elie Matta
2) Réécrira le même exercice en utilisant une classe qui contient deux fonctions qui s?appellent
somme_for et somme_while
Public Class Class1
Public Function sum_for(ByVal t() As Integer) As Integer
Dim s As Integer = 0
For i As Integer = 0 To t.Length - 1
s += t(i)
Next i
Return s
End Function
Public Function sum_while(ByVal t() As Integer) As Integer
Dim s As Integer = 0
Dim i As Integer = 0
While i < t.Length
s += t(i)
i += 1
End While
Return s
End Function
End Class
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button2.Click
Dim k(5) As Integer
For i As Integer = 0 To k.Length - 1
k(i) = CInt(InputBox("entre l'elemnet numero: " & i + 1))
Next i
Dim c As New Class1
Dim somme As Integer = c.sum_for(k)
("somme par methode for: " & somme)
somme = c.sum_while(k)
("somme par methode while: " & somme)
End Sub
Copyright © 2010-2011, . All rights reserved Page 9
Cours, Exemples et Exercices de la matière et
Préparé par Elie Matta
End Sub
Public Function Rcust(ByVal ID As Integer) As customer
If ID < acustomer.Length - 1 Then
Return acustomer(ID)
Else
("ID INVALID")
End
End If
''Try
'' Return acustomer(ID)
''Catch ex As IndexOutOfRangeException
'' ("Not included" & ex.Message.ToString)
''End Try
End Function
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button2.Click
()
End Sub
End Class
Form2:
Public Class Form2
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Dim cust1 As Form1.customer
cust1 = Form1.Rcust(CInt())
(.ToString)
(.ToString)
(.ToString)
(.ToString)
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button2.Click
ListBox1.Items.Clear()
End Sub
End Class
Copyright © 2010-2011, . All rights reserved Page 11
Cours, Exemples et Exercices de la matière et
Préparé par Elie Matta
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button2.Click
Dim a As New guest("test", "password")
Dim b As String
b = a.f()
(b)
End Sub
End Class
Exercice 7
Modifier le code précédent tout en remplaçant les constructeurs par des fonctions
Class user
Private ssn As String
Protected pass As String
Sub s2(ByVal s As String, ByVal p As String)
s = ssn
p = pass
End Sub
End Class
Class guest
Inherits user
Private ssn2 As String
Sub s1(ByVal s2 As String, ByVal p2 As String)
MyBase.s2(s2, p2) 'appel du constructeur de la classe parente
ssn2 = s2
End Sub
Function f() As String
Return ssn2 & pass
End Function
End Class
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button2.Click
Dim g As New guest()
g.s1("aa", "bb")
Dim r As String
r = g.f()
(r)
End Sub
End Class
Exercices 8 :
Dans la solution précédent essayez de remplaces l?accesseur private dans la classe user par public
ReadOnly ssn as string et commenter
Lorsqu?on déclare une variable readonly on peut seulement l?initialiser à l?intérieur d?un
constructeur
Copyright © 2010-2011, . All rights reserved Page 13
Cours, Exemples et Exercices de la matière et
Préparé par Elie Matta
Exercices 10: Primary Key, Package et Sous Package, Overrides, Overridable, Shared
Solution
Imports .SqlClient
Imports
Imports .OleDb
Public Class Connexion
Dim s As String = ".OLEDB.12.0;Data
Source=|DataDirectory|\.accdb"
Dim conn As OleDbConnection
Dim mycommand As OleDbCommand
Public Sub dispose()
conn.Close()
End Sub
Public Sub usebuilder(ByVal ds As DataSet, ByVal adp As OleDbDataAdapter)
Dim builder As New OleDbCommandBuilder(adp)
adp.Update(ds)
End Sub
End Class
Form1
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles
End Sub
Class Package
Protected pid As Int16 'protected car pid doit etre incrementer dans le constructeur
Public pname As String
Public is_sp As Boolean
Public Shared packs As New ArrayList 'on va creer plusieurs instances c'est pour
quoi on a mis shared
Sub New()
pid = packs.Count 'pour incrementer le pid automatiquement
End Sub
Public Function Create_Package(ByVal name As String, ByVal is_sp As Boolean) As
Int16 'pour retrouner le pid
Me.pname = name
Me.is_sp = is_sp
If is_sp = False Then
(Me)
Else
Dim p As New Package
Copyright © 2010-2011, . All rights reserved Page 15
Cours, Exemples et Exercices de la matière et
Préparé par Elie Matta
Public Overrides Sub GetDetails(ByVal id As Int16)
For i As Integer = 0 To packs.Count - 1
Dim pkg As sppackage = sppacks(i) 'ctype(packs(i),package)
If = id Then
MsgBox(pkg.pname.ToString() & " - " & pkg.is_sp.ToString() & "-" &
pkg.status.ToString())
Exit For
End If
Next i
End Sub
Public Overrides Sub delete_pkg(ByVal id As Int16)
sppacks.RemoveAt(id)
End Sub
End Class
Copyright © 2010-2011, . All rights reserved Page 17
Cours, Exemples et Exercices de la matière et
Préparé par Elie Matta
Exercice 12:
1. Create a DataSet
2. Create a DataTable
a. Add a primary key
3. Add Data (try to create duplication in the dataset)
4. Modify Data (utiliser Find)
5. Delete Data
Dr.delete()
Ds.tables(0).rows.Remove(dr)
i. Ds.rejectchanges
ii. Ds.acceptchanges
Solution:
1) dim ds as new DataSet
2) dim tbl as new DataTable("Authors")
(“Auid”,.GetType("System.Int32"))
(“AuLName”,.GetType("System.String"))
(“AuFName”,.GetType("System.String"))
(tbl)
2- a. dim pk(0) as DataColumns
pk(0)= tbl.Columns("Auid")
tbl.Primarykey = pk
3) dim dr as DataRow
dr = ds.Table(0).NewRow „ou tbl.NewRow
dr(0) = 1
dr(1) = “au_lname1”
dr(2) = “au_fname1”
(dr)
dr= tbl.NewRow
dr(0) = 1
dr(1)= 2
dr(2)=2
(dr)
4) Modify
dr= tbl.NewRow
dr(0)= 2
dr(1)= " "
dr(2)=" "
(dr)
Copyright © 2010-2011, . All rights reserved Page 20
Cours, Exemples et Exercices de la matière et
Préparé par Elie Matta
Find the author AuID=1 by using rhe primaryKey
dim dr2 as DataRow
dr2 = (1)
dr(1)="New_auLname1"
5) fetch a row
dim dr3 as DataRow
dr3 = (2)
dr3.Delete() „i. on peut le restaurer avec reject changes
.Remove(dr3) „ii.
i) use of Acceptchanges
tbl.AcceptChanges//show in dataGrid View
ii) add/modify/delete new row
tbl.RejectChanges
in DataGridView
Copyright © 2010-2011, . All rights reserved Page 21
Cours, Exemples et Exercices de la matière et
Préparé par Elie Matta
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
()
End Sub
End Class
Exercice 13: sur le Timer avec UserControlWindowsApplication8
UserControl :
Public Class UserControl1
Private Bcolor = Nothing
Private Fcolor = Nothing
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles
= Format(Now, "hh:mm:ss")
End Sub
Property ClockBackColor() As Color
Get
Return Bcolor
End Get
Set(ByVal value As Color)
Bcolor = value
Label1.BackColor = Bcolor
End Set
End Property
Property ClockForeColor() As Color
Get
Return Fcolor
End Get
Set(ByVal value As Color)
Fcolor = value
Label1.ForeColor = Fcolor
End Set
End Property
Private Sub UserControl1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles
End Sub
End Class
Exemple 14 : sur le UserControl (Timer/ Enter)WindowsApplication5
Imports .OleDb
Public Class Connection
Dim con As OleDbConnection
Dim mycommand As OleDbCommand
Copyright © 2010-2011, . All rights reserved Page 23
Cours, Exemples et Exercices de la matière et
Préparé par Elie Matta
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button5.Click
CustomControl11.enabled = True
End Sub
End Class
Dans ClassLibrary2 ()
Public Class CustomControl1
Inherits System.ComponentModel.Component
Public input As String
Public Event finished(ByVal str As String)
Private WithEvents localtimer As System.Timers.Timer
Public Property enabled() As Boolean
Get
Return localtimer.Enabled
End Get
Set(ByVal value As Boolean)
localtimer.Enabled = value
End Set
End Property
Private Sub localtimer_tick(ByVal s As Object, ByVal e As Timers.ElapsedEventArgs)
Handles localtimer.Elapsed
RaiseEvent finished(input)
End Sub
Public Overloads Sub dispose()
MyBase.Finalize()
localtimer.Enabled = False
localtimer.Dispose()
MyBase.Dispose()
End Sub
Public Sub New()
()
InitializeComponent()
localtimer = New SYstem.Timers.Timer
localtimer.Enabled = False
localtimer.Interval = 4000
End Sub
End Class
Copyright © 2010-2011, . All rights reserved Page 27
Cours, Exemples et Exercices de la matière et
Préparé par Elie Matta
Windows Forms
I. Why use windows form?
1. Rich of controls
2. Advanced printing support :
a. Page setup dialog
b. Print preview control
c. Print preview dialog
d. Print dialog
3. Advanced GDI+
a. System.Drawing.Drawing2D
b. System.Drawing.Imaging
c.
4. Visual inheritance a : WForm are classes -> we can benefit from inheritance
5. Extensible object model : We can extend the class library
6. Advanced forms design
II.
Component
IComponents
IDisposable
Control
Sizing
visibility
ScrolableControl
taborder
Scrolling
ContainerControl
Tabing
Form
Focus
VSControl
Copyright © 2010-2011, . All rights reserved Page 29
Cours, Exemples et Exercices de la matière et
Préparé par Elie Matta
Destructeur : automatiquement appelle lorsqu?on ferme le formulaire
Non-Modal: the destructor is auto called when we close the form
Modal: we have to call the Dispose() manually
V. Form Proprieties
-Dialog Result
Button 17 dans le cours
-Opacity and focus
-AcceptButton and CancelButton
VI.
Form Methods
-Close
-Show
-ShowDialog
VII.
Form Events
-Activated, Deactivate
Exercices:
a. En utilisant deux méthodes différentes écrire le code correspondant pour manipuler les
événements suivants : Form1_Activated, Form1_Closed, Form1_Desactivate,
Form1_SizeChanged
b. En utilisant un formulaire modal traité les cas Ok, Cancel, Abort et Retry
Solution : WindowsApplication14
Form1:
Public Class Form1
Private Sub Form1_Activated(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles MyBase.Activated
= "Activated"
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles
AddHandler Me.FormClosed, AddressOf MyForm_ClickClosed
End Sub
Private Sub Form1_FormClosed(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.FormClosedEventArgs) Handles MyBase.FormClosed
MsgBox("Closed")
End Sub
Copyright © 2010-2011, . All rights reserved Page 31
Cours, Exemples et Exercices de la matière et
Préparé par Elie Matta
End Sub
Private Sub TextBox2_DragEnter(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.DragEventArgs) Handles TextBox2.DragEnter
If e.Data.GetDataPresent() Then
e.Effect =
End If
End Sub
Private Sub TextBox2_DragDrop(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.DragEventArgs) Handles TextBox2.DragDrop
Dim str As String = e.Data.GetData().ToString()
Me.TextBox2.SelectedText = str + vbCrLf
End Sub
End Class
Copyright © 2010-2011, . All rights reserved Page 34