85
Practical File Visual Basic & Web Technology MT-CSE 160 Submitted To: Submitted by: 1

Vb Practical File

Embed Size (px)

Citation preview

Page 1: Vb Practical File

Practical File

Visual Basic & Web TechnologyMT-CSE 160

Submitted To: Submitted by:

SAMALKHA GROUP OF INSTITUTIONS

1

Page 2: Vb Practical File

Practical – 1

LOADING CONTROLS AT RUNTIME: Write a program which demonstrates the loading of controls at runtime.

Dim i As IntegerDim lblindex As Integer

Dim btnindex As IntegerPrivate Sub cmd_btn_Click(Index As Integer)' first give the index =0 to command button at design timeLoad cmd_btn(btnindex)With cmd_btn(btnindex).Caption = "Button " & btnindex.Left = 3800.Top = 1200 + btnindex * 500.Height = 300.Visible = TrueEnd Withbtnindex = btnindex + 1End Sub

Private Sub cmd_lbl_Click()Set lblnew = Controls.Add("VB.Label", "Labels" & lblindex)With lblnew.Caption = "Label " & lblindex.Left = 800.Top = 1200 + lblindex * 500.Visible = TrueEnd Withlblindex = lblindex + 1End Sub

Private Sub cmd_Remove_Button_Click()If btnindex > 1 Thenbtnindex = btnindex - 1Unload cmd_btn(btnindex)ElseMsgBox ("There is no Button to remove")

2

Page 3: Vb Practical File

End IfEnd Sub

Private Sub cmd_remove_Label_Click()If lblindex > 1 Thenlblindex = lblindex - 1Me.Controls.Remove ("Labels" & lblindex)ElseMsgBox ("There is no label to remove")

End If

End Sub

Private Sub cmd_Remove_Tbox_Click()If i > 1 Theni = i - 1Me.Controls.Remove ("TextBox" & i)ElseMsgBox ("There is no TextBox to remove")

End If

End Sub

Private Sub cmd_tbox_Click()Set txtnew = Controls.Add("VB.TextBox", "TextBox" & i) txtnew.Text = "TextBox " & i ' move left, top, width , height txtnew.Move 2200, 1200 + i * 500, 1400, 20 txtnew.Visible = True i = i + 1End Sub

Private Sub Form_Load()i = 1btnindex = 1lblindex = 1

3

Page 4: Vb Practical File

End Sub

4

Page 5: Vb Practical File

Practical – 2

DYNAMIC MENUS: Write a program which demonstrates the dynamic menus. For example the recently visited files are added in menus which changes dynamically.

Dim Index As IntegerPrivate Sub cmd_execute_Click()

If Index < 5 ThenIndex = Index + 1Load FileRecent(Index)FileRecent(Index).Enabled = TrueEnd If

Dim i As Integeri = IndexDo While i > 1FileRecent(i).Caption = FileRecent(i - 1).Captioni = i - 1Loop

FileRecent(1).Caption = tbox_command.Text

tbox_command.Text = ""tbox_command.SetFocusEnd Sub

Private Sub FileExit_Click()EndEnd Sub

Private Sub FileRecent_Click(Index As Integer)tbox_command.Text = FileRecent(Index).CaptionEnd Sub

Private Sub FileReset_Click()For i = 1 To IndexUnload FileRecent(i)Next

5

Page 6: Vb Practical File

End Sub

Private Sub Form_Load()FileRecent(0).Enabled = FalseEnd Sub

6

Page 7: Vb Practical File

Practical – 3

ANALOG CLOCK: Write a program to create an analog clock, which shows all the three hands (Hour, Minute and second). You can add an option to change the background of the clock.

Dim min, hour As IntegerConst PI = 3.14159265 'Pi constant

Dim theta As SingleDim dtheta As SingleDim second As LongDim cx As SingleDim cy As SingleDim radius As SingleConst stheta As Single = 4.7142857

Private Sub btn_image_Click()CommonDialog1.Filter = "Graphics|*.bmp;*.gif;*.jpg|Text File|*.txt|All Files|*.*"CommonDialog1.ShowOpen

If Not Picture1.AutoRedraw Then Picture1.AutoRedraw = True

Picture1.Picture = LoadPicture(CommonDialog1.Filename)Picture1.PaintPicture Picture1.Picture, 0, 0, 5000, 5000gettimeEnd Sub

Public Sub gettime()theta = sthetadtheta = 2 * PI / 60

cx = 2500cy = 2500radius = 2300second = Format(Time, "s") + Format(Time, "n") * 60 + (Format(Time, "h") Mod 12) * 3600min = second / 60hour = Format(Time, "h") Mod 12

7

Page 8: Vb Practical File

LineSec.X1 = 2500LineSec.Y1 = 2500theta = stheta + (second Mod 60) * dtheta

LineSec.x2 = cx + (radius - 100) * Cos(theta)LineSec.y2 = cy + (radius - 100) * Sin(theta)

line_minute.X1 = 2500line_minute.Y1 = 2500

line_Hour.X1 = 2500line_Hour.Y1 = 2500

line_Hour.x2 = cx + (radius - 200) * Cos(stheta + (2 * PI / 3600) * min * 5)line_Hour.y2 = cy + (radius - 200) * Sin(stheta + (2 * PI / 3600) * min * 5)End Sub

Private Sub cmd_ForeColor_Click()CommonDialog1.ShowColorFor i = 0 To Label14.Count - 1Label14(i).ForeColor = CommonDialog1.colorNext iShape1.BorderColor = CommonDialog1.colorDrawCircle 2500, 2500, 2400, 60, CommonDialog1.colorEnd Sub

Private Sub Form_Load()'LoadDotsDrawCircle 2500, 2500, 2400, 60gettimeEnd Sub

Private Sub Timer2_Timer()second = second + 1theta = theta + dthetaline_minute.x2 = cx + (radius - 100) * Cos(stheta + (2 * PI / 3600) * second)line_minute.y2 = cy + (radius - 100) * Sin(stheta + (2 * PI / 3600) * second)If second Mod 60 = 0 Then

8

Page 9: Vb Practical File

theta = 4.7142857min = min + 1

line_Hour.x2 = cx + (radius - 200) * Cos(stheta + (2 * PI / 3600) * min * 5)line_Hour.y2 = cy + (radius - 200) * Sin(stheta + (2 * PI / 3600) * min * 5)

If second = 43200 Then second = 0End If

If min = 720 Thenmin = 0End If

X = cx + radius * Cos(theta) Y = cy + radius * Sin(theta) LineSec.x2 = X LineSec.y2 = YEnd Sub

Private Sub DrawCircle(ByVal cx As Single, ByVal cy As Single, ByVal radius As Single, ByVal num_segments As Integer, Optional fcolor As ColorConstants)Const PI = 3.14159265Dim X As SingleDim Y As SingleDim theta As SingleDim dtheta As SingleDim second As Integer

For i = 1 To Dot.Count - 1Unload Dot(i)Next

dtheta = 2 * PI / num_segments theta = stheta For seg = 1 To num_segments theta = theta + dtheta X = cx + radius * Cos(theta)

9

Page 10: Vb Practical File

Y = cy + radius * Sin(theta) Load Dot(seg) Dot(seg).X1 = X Dot(seg).Y1 = Y Dot(seg).x2 = X + 2 Dot(seg).y2 = Y + 2 Dot(seg).BorderWidth = 3 If seg Mod 5 = 0 Then Dot(seg).BorderWidth = 5 Else Dot(seg).BorderColor = fcolor End If Dot(seg).Visible = True Next seg End Sub

10

Page 11: Vb Practical File

Practical – 4

RESUME WRITER: Create an application such that it will collect the Personal, Educational, and Professional information from a candidate and creates resume in rich text format automatically.

Const RTF_NUMSTART As String = _ "{\rtf1\ansi\deff0\deftab720{\fonttbl{\f0\fswiss MS Sans Serif;}{\f1\froman\fcharset2 Symbol;}{\f2\fnil\fprq2\fcharset2 Wingdings;}{\f3\froman\fprq2 Times New Roman;}}" & vbCrLf & _ "{\colortbl\red0\green0\blue0;}" & vbCrLf & _ "\deflang1033\pard\li720\fi-360\plain\f3\fs24"Const RTF_NUMITEM As String = _ "\par @%@.\tab "Const RTF_NUMEND As String = "\par }"Dim sex As String

Private Sub btn_more_edu_Click()Dim eindex As Integereindex = tbox_course.Count

If eindex > 8 ThenMsgBox ("Course completed")Exit SubEnd If

Load tbox_course(eindex)With tbox_course(eindex).Height = tbox_course(eindex - 1).Height.Width = tbox_course(eindex - 1).Width.Left = tbox_course(eindex - 1).Left.Top = tbox_course(eindex - 1).Top + tbox_course(eindex - 1).Height + 100.Text = "".Visible = TrueEnd With

11

Page 12: Vb Practical File

Load tbox_iname(eindex)With tbox_iname(eindex).Height = tbox_iname(eindex - 1).Height.Width = tbox_iname(eindex - 1).Width.Left = tbox_iname(eindex - 1).Left.Top = tbox_iname(eindex - 1).Top + tbox_iname(eindex - 1).Height + 100.Visible = TrueEnd With

Load tbox_stream(eindex)With tbox_stream(eindex).Height = tbox_stream(eindex - 1).Height.Width = tbox_stream(eindex - 1).Width.Left = tbox_stream(eindex - 1).Left.Top = tbox_stream(eindex - 1).Top + tbox_stream(eindex - 1).Height + 100.Visible = TrueEnd With

Load tbox_board(eindex)With tbox_board(eindex).Height = tbox_board(eindex - 1).Height.Width = tbox_board(eindex - 1).Width.Left = tbox_board(eindex - 1).Left.Top = tbox_board(eindex - 1).Top + tbox_board(eindex - 1).Height + 100.Visible = TrueEnd With

Load tbox_pyear(eindex)With tbox_pyear(eindex).Height = tbox_pyear(eindex - 1).Height.Width = tbox_pyear(eindex - 1).Width.Left = tbox_pyear(eindex - 1).Left.Top = tbox_pyear(eindex - 1).Top + tbox_pyear(eindex - 1).Height + 100.Visible = TrueEnd With

Load tbox_per(eindex)With tbox_per(eindex).Height = tbox_per(eindex - 1).Height.Width = tbox_per(eindex - 1).Width

12

Page 13: Vb Practical File

.Left = tbox_per(eindex - 1).Left

.Top = tbox_per(eindex - 1).Top + tbox_per(eindex - 1).Height + 100

.Visible = TrueEnd With

If eindex > 4 ThenLoad Label9(eindex)With Label9(eindex).Height = Label9(eindex - 1).Height.Width = Label9(eindex - 1).Width.Left = Label9(eindex - 1).Left.Top = tbox_course(eindex).Top.Caption = "Other".Visible = TrueEnd WithEnd IfEnd Sub

Private Sub calendar_dob_DblClick()calendar_dob.Visible = Falsetbox_DOB.Text = calendar_dob.ValueEnd Sub

Private Sub cmd_dob_Click()calendar_dob.Visible = Not calendar_dob.VisibleEnd Sub

Private Sub cmd_enext_Click()SSTab1.Tab = 2End Sub

Private Sub cmd_more_Click()Dim pindex As Integerpindex = tbox_exper.Count

If pindex > 8 ThenMsgBox ("Experience done")Exit SubEnd If

13

Page 14: Vb Practical File

Load tbox_exper(pindex)With tbox_exper(pindex).Height = tbox_exper(pindex - 1).Height.Width = tbox_exper(pindex - 1).Width.Left = tbox_exper(pindex - 1).Left.Top = tbox_exper(pindex - 1).Top + tbox_exper(pindex - 1).Height + 100.Visible = TrueEnd With

Load tbox_company(pindex)With tbox_company(pindex).Height = tbox_company(pindex - 1).Height.Width = tbox_company(pindex - 1).Width.Left = tbox_company(pindex - 1).Left.Top = tbox_company(pindex - 1).Top + tbox_company(pindex - 1).Height + 100.Visible = TrueEnd With

Load tbox_from(pindex)With tbox_from(pindex).Height = tbox_from(pindex - 1).Height.Width = tbox_from(pindex - 1).Width.Left = tbox_from(pindex - 1).Left.Top = tbox_from(pindex - 1).Top + tbox_from(pindex - 1).Height + 100.Visible = TrueEnd With

Load tbox_to(pindex)With tbox_to(pindex).Height = tbox_to(pindex - 1).Height.Width = tbox_to(pindex - 1).Width.Left = tbox_to(pindex - 1).Left.Top = tbox_to(pindex - 1).Top + tbox_to(pindex - 1).Height + 100.Visible = TrueEnd With

Load tbox_desig(pindex)With tbox_desig(pindex).Height = tbox_desig(pindex - 1).Height.Width = tbox_desig(pindex - 1).Width

14

Page 15: Vb Practical File

.Left = tbox_desig(pindex - 1).Left

.Top = tbox_desig(pindex - 1).Top + tbox_desig(pindex - 1).Height + 100

.Visible = TrueEnd With

Load tbox_tech(pindex)With tbox_tech(pindex).Height = tbox_tech(pindex - 1).Height.Width = tbox_tech(pindex - 1).Width.Left = tbox_tech(pindex - 1).Left.Top = tbox_tech(pindex - 1).Top + tbox_tech(pindex - 1).Height + 100.Visible = TrueEnd With

End Sub

Private Sub cmd_pnext_Click()SSTab1.Tab = 1End Sub

Private Sub cmd_pronext_Click()SSTab1.Tab = 3build_resumeEnd Sub

Function build_resume()

Dim str As Stringstr = ""str = RTF_NUMSTART & " \qc \b " & tbox_name.Text & "\b0 \par "str = str & " \qc " & tbox_city.Text & ", " & tbox_state.Text & " \par " & "\b Mobile : " & tbox_mobile & " \par " & tbox_email.Text & " \par "

str = str & "\ql Summary" & " \b0 \par \bullet \tab " & "Quick Learner with the ability to work under pressure & willingness to enhance knowledge." & " \par \bullet \tab " & _ "Proficiency at grasping technical concept quickly and implementing them in an effective manner." & " \par \bullet \tab " & _"Hard Working, Time Management, Punctuality & having good attitude." & " \par \par "

str = str & " \b Education \b0 \par "

15

Page 16: Vb Practical File

Dim i As IntegerDim education As Stringi = tbox_course.CountWhile i > 0 i = i - 1 If tbox_course(i).Text <> "" Then education = education & " \bullet\tab " & tbox_course(i).Text If tbox_stream(i).Text <> "" Then education = education & " in " & tbox_stream(i).Text End If education = education & " from " & tbox_iname(i).Text & " (" & tbox_board(i).Text & ") in " & tbox_pyear(i).Text & " with scoring " & tbox_per(i).Text & "%. \par " End If Wendstr = str & educationDim prof As StringIf tbox_exper(0).Text <> "" Thenprof = prof & " \par\par \b Experience \b0\par"

i = tbox_exper.CountWhile i > 0 i = i - 1 If tbox_exper(i).Text <> "" Then prof = prof & " \bullet\tab " & tbox_exper(i).Text & " in " & tbox_tech(i).Text & ", from " & tbox_from(i).Text & " to " & tbox_to(i).Text prof = prof & " in " & tbox_company(i).Text & " at Designation " & tbox_desig(i).Text & " \par" End If WendEnd Ifstr = str & profstr = str & "\par \b " & "Personal Detail" & " \b0\par" & " Father's Name :" & tbox_fname.Text & "\par" & " Date of Birth :" & tbox_DOB.Text & "\par Gender :" & sex & " \par" & " Marital Status :" & cbox_status.SelText & " \par " & " Address :" & tbox_address.Text & " \par "

16

Page 17: Vb Practical File

str = str & " \par\b Declaration:\b0\par " & " I here by declare that the above information are true to the best of my knowledge and belief and can be supported by reliable documents when needed."str = str & "\par\par Date: \tab\tab\tab\tab\tab\tab\tab\tab\tab (" & UCase(tbox_name.Text) & ")"

'rtb_resume.SelAlignment = vbLeftJustifyrtb_resume.TextRTF = str & RTF_NUMENDEnd Function

Private Sub Form_Load()sex = "Male"cbox_status.ListIndex = 0End Sub

Private Sub opt_sexFemale_Click()sex = "Female"End Sub

Private Sub opt_sexMale_Click()sex = "Male"End Sub

17

Page 18: Vb Practical File

18

Page 19: Vb Practical File

Practical – 5

PICTURE VIEWER: Create a program that enables the users to open and choose files from the folders in their PC. The picture viewer provides the functionality to move to the NEXT and PREVIOUS photos, ZOOM IN & ZOOM OUT

Dim Index As IntegerDim path As StringDim X, Y As Integer

Private Sub bnt_prev_Click()If Index > 0 ThenIndex = Index - 1End If

path = File1.pathIf Right(path, Len(path) - 2) <> "\" Thenpath = path & "\"End IfPictureViewer.Picture1.Picture = LoadPicture(path & File1.List(Index))PictureViewer.Picture1.PaintPicture PictureViewer.Picture1.Picture, 0, 0, 800, 600End Sub

Private Sub btn_next_Click()If Index < File1.ListCount - 1 ThenIndex = Index + 1

path = File1.pathIf Right(path, Len(path) - 2) <> "\" Thenpath = path & "\"End IfPicture1.Picture = LoadPicture(path & File1.List(Index))Picture1.PaintPicture Picture1.Picture, 0, 0, 800, 600Picture2.Picture = LoadPicture(path & File1.List(Index))End If

End Sub

Private Sub btn_open_Click()openFolderDialog.Show 1

19

Page 20: Vb Practical File

End Sub

Private Sub btn_zoomin_Click()

If Picture1.Picture = 0 ThenExit SubEnd If

X = X + 80Y = Y + 60Picture1.Height = YPicture1.Width = XPicture1.PaintPicture Picture1.Picture, 0, 0, X, Y

If X > Pic_holder.ScaleWidth Then

HScroll1.Max = X - Pic_holder.ScaleWidthVScroll1.Max = Y - Pic_holder.ScaleHeightElseHScroll1.Max = 0VScroll1.Max = 0End If

End Sub

Private Sub btn_zoomout_Click()If Picture1.Picture = 0 ThenExit SubEnd If

If X > 160 ThenX = X - 80Y = Y - 60End IfPicture1.Height = YPicture1.Width = XPicture1.PaintPicture Picture1.Picture, 0, 0, X, YIf Picture1.ScaleWidth - Pic_holder.ScaleWidth > 0 ThenHScroll1.Max = Picture1.ScaleWidth - Pic_holder.ScaleWidthVScroll1.Max = Picture1.ScaleHeight - Pic_holder.ScaleHeight

20

Page 21: Vb Practical File

ElseHScroll1.Max = 0VScroll1.Max = 0End IfEnd Sub

Private Sub Form_Load()X = 800Y = 600

'Set up picturebox With Picture1 .ScaleMode = vbPixels .AutoRedraw = True

.DrawMode = vbInvert .DrawStyle = SelDrawType .BackColor = vbWhite .MousePointer = vbCrosshair

.Left = 0 .Top = 0 .ScaleHeight = Pic_holder.ScaleHeight .ScaleWidth = Pic_holder.ScaleWidth End WithPicture2.ScaleHeight = Picture1.ScaleHeightPicture2.ScaleWidth = Picture1.ScaleWidth HScroll1.Max = Picture1.ScaleWidth - Pic_holder.ScaleWidthHScroll1.min = 0

VScroll1.Max = Picture1.ScaleHeight - Pic_holder.ScaleHeightHScroll1.min = 0End Sub

Private Sub HScroll1_Change()Picture1.Left = -HScroll1.Value

End Sub

21

Page 22: Vb Practical File

Private Sub VScroll1_Change()Picture1.Top = -VScroll1.ValueEnd Sub

22

Page 23: Vb Practical File

Practical – 6

TIC- TAC- TOE: Develop a program Tic Tac Toe in VB so that you can play the game virtually. First of all, you need to draw the interface with four straight lines, then insert nine image controls and make them an array, Image1 (0) to Image1 (8). Secondly, insert two pictures, one is a circle and the other one is a cross to represent player 1 and player2.

Dim sym As StringDim winr(9) As StringPrivate Sub Form_Load()sym = "X"Dim i As IntegerFor i = 0 To 8winr(i) = iNext iEnd Sub

Private Sub Label1_Change()If Label1.Caption = "Player 1" Thensym = "X"Elsesym = "0"End IfEnd Sub

Private Sub lbl_gstatus_Click(Index As Integer)If lbl_gstatus(Index).Caption = "" Thenlbl_gstatus(Index).Caption = symwinr(Index) = symIf Label1.Caption = "Player 1" ThenLabel1.Caption = "Player 2"ElseLabel1.Caption = "Player 1"End IfcheckEnd IfEnd Sub

Function check()Dim i As IntegerDim won As Boolean

23

Page 24: Vb Practical File

Dim psymbol As StringIf winr(0) = winr(1) And winr(1) = winr(2) Thenwon = Truepsymbol = winr(0)ElseIf winr(2) = winr(4) And winr(4) = winr(6) Thenwon = Truepsymbol = winr(2)ElseIf winr(0) = winr(3) And winr(3) = winr(6) Thenwon = Truepsymbol = winr(0)ElseIf winr(1) = winr(4) And winr(4) = winr(7) Thenwon = Truepsymbol = winr(1)ElseIf winr(2) = winr(5) And winr(5) = winr(8) Thenwon = Truepsymbol = winr(2)ElseIf winr(0) = winr(1) And winr(1) = winr(2) Thenwon = Truepsymbol = winr(0)ElseIf winr(3) = winr(4) And winr(4) = winr(5) Thenwon = Truepsymbol = winr(3)ElseIf winr(6) = winr(7) And winr(7) = winr(8) Thenwon = Truepsymbol = winr(6)End IfIf won = True ThenDim pno As IntegerIf psymbol = "X" Thenpno = 1Elsepno = 2End IfMsgBox (" Player " & pno & " won")won = FalseFor i = 0 To 8winr(i) = ilbl_gstatus(i).Caption = ""Label1.Caption = "Player 1"Next i

24

Page 25: Vb Practical File

End IfEnd Function

25

Page 26: Vb Practical File

Practical – 7

A DRAG & DROP RECYCLE_BIN: Make a drag and drop program that resembles a recycle bin. Drag and drop is a common windows application where you can drag and drop an object such as a file into a folder or into a recycle bin. This capability can be easily programmed in visual basic

Private Sub Picture1_DragDrop(Source As Control, X As Single, Y As Single)Source.Visible = FalseEnd Sub

Private Sub Picture1_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single)If Button = vbRightButton ThenPopupMenu RestoreMenu, vbPopupMenuRightAlignEnd IfEnd Sub

Private Sub Restore_Click()Image1.Visible = TrueImage2.Visible = TrueImage3.Visible = TrueImage4.Visible = TrueEnd Sub

26

Page 27: Vb Practical File

27

Page 28: Vb Practical File

Practical – 8

TRAFFIC LIGHT: Create a Traffic light program in which, one can insert one timer and sets its interval according to its desire. Suppose set it to 3000, which is equivalent to 3 seconds. Next you insert three shapes and set their shape properties to circle and fill the colors.

Dim status(4) As BooleanConst interval As Integer = 1000Dim wait As IntegerDim waittime(3) As IntegerDim stage, t1, t2, t3, t4 As Integer

Private Sub Command1_Click()Me.FillColor = vbRedMe.FillStyle = vbSolid

Call light(250, 50, 1)Call light(100, 200, 1)Call light(400, 200, 1)Call light(250, 300, 1)waittime(0) = 10waittime(1) = 4waittime(2) = 8Timer2.Enabled = TrueTimer1.Enabled = Truet1 = waittime(0) + waittime(1)t2 = (waittime(1) + waittime(2)) * 2 + 1t3 = (waittime(1) + waittime(2)) * 3 + 1t4 = (waittime(1) + waittime(2)) * 4 + 1Label1.Left = 320Label1.Top = 50Label2.Left = 320Label2.Top = 300Label3.Left = 170Label3.Top = 200Label4.Left = 470Label4.Top = 200wait = 10stage = 0End Sub

28

Page 29: Vb Practical File

Function light(X As Integer, Y As Integer, Optional c As Integer)

Call rectangle(X, Y, X + 50, Y + 100)Call fillcircle(X + 25, Y + 20, vbWhite)Call fillcircle(X + 25, Y + 50, vbWhite)Call fillcircle(X + 25, Y + 80, vbWhite)

Select Case cCase 1:Call fillcircle(X + 25, Y + 20, vbRed)Case 2:Call fillcircle(X + 25, Y + 50, vbYellow)Case 3:Call fillcircle(X + 25, Y + 80, vbGreen)End SelectEnd Function

Function rectangle(X As Integer, Y As Integer, x2 As Integer, y2 As Integer)Me.Line (X, Y)-(X, y2), vbRedMe.Line (x2, Y)-(x2, y2), vbRedMe.Line (X, Y)-(x2, Y), vbRedMe.Line (X, y2)-(x2, y2), vbRed

End FunctionFunction fillcircle(X As Integer, Y As Integer, color As ColorConstants)Me.FillColor = colorMe.Circle (X, Y), 10, vbBlackEnd Function

Private Sub Timer1_Timer()

t1 = t1 - 1t2 = t2 - 1t3 = t3 - 1t4 = t4 - 1

Label1.Caption = t1Label2.Caption = t2Label3.Caption = t3

29

Page 30: Vb Practical File

Label4.Caption = t4

End Sub

Private Sub Timer2_Timer()stage = stage + 1Select Case stageCase 1:Call light(250, 50, 2)Timer2.interval = interval * waittime(1)Case 2:Call light(250, 50, 3)Call light(400, 200, 1)t1 = waittime(2)Timer2.interval = interval * waittime(2)Case 3:Call light(250, 50, 2)Call light(250, 300, 2)t1 = (waittime(1) + waittime(2)) * 3 + waittime(1)Timer2.interval = interval * waittime(1)Case 4:Call light(250, 50, 1)Call light(250, 300, 3)t2 = waittime(2)Timer2.interval = interval * waittime(2)Case 5:Call light(100, 200, 2)Call light(250, 300, 2)t2 = (waittime(1) + waittime(2)) * 3 + waittime(1)Timer2.interval = interval * waittime(1)Case 6:Call light(100, 200, 3)Call light(250, 300, 1)t3 = waittime(2)Timer2.interval = interval * waittime(2)Case 7:Call light(100, 200, 2)Call light(400, 200, 2)t3 = (waittime(1) + waittime(2)) * 3 + waittime(1)Timer2.interval = interval * waittime(1)

30

Page 31: Vb Practical File

Case 8:Call light(100, 200, 1)Call light(400, 200, 3)t4 = waittime(2)Timer2.interval = interval * waittime(2)Case 9:Call light(250, 50, 2)Call light(400, 200, 2)t4 = (waittime(1) + waittime(2)) * 3 + waittime(1)Timer2.interval = interval * waittime(1)stage = 1End Select

End Sub

31

Page 32: Vb Practical File

Practical – 9

CUBIC FUNCTION GRAPH PLOTTER: Make a program that enables users to input the coefficients of a cubic equation and draw its graph. The cubic equation takes the form ax3+bx2+cx+d.

Private Sub btn_cls_Click()pic_graph.ClsEnd Sub

Private Sub cmd_draw_Click()Dim a, b, c, d As IntegerDim w, v As Doublea = Val(tbox_a.Text)b = Val(tbox_b.Text)c = Val(tbox_c.Text)d = Val(tbox_d.Text)

'Using a scale of 0.5 cm to represent i unit to draw the graph' Need to make some transformation as the coordinates in VB start from top left

For w = 0 To 10 Step 0.001v = a * (5 - w) ^ 3 + b * (5 - w) ^ 2 + c * (5 - w) + dpic_graph.PSet (w, 5 - v)

Next wEnd Sub

Private Sub Form_Load()Line_x.X1 = 0Line_x.x2 = pic_graph.ScaleWidthLine_x.Y1 = pic_graph.ScaleHeight / 2Line_x.y2 = pic_graph.ScaleHeight / 2

Line_y.X1 = pic_graph.ScaleWidth / 2Line_y.x2 = pic_graph.ScaleWidth / 2Line_y.Y1 = 0Line_y.y2 = pic_graph.ScaleHeightEnd Sub

32

Page 33: Vb Practical File

33

Page 34: Vb Practical File

Practical – 10

GEOMETRIC PROGRESSION: Make a Visual Basic program that can compute a geometric progression and display the results in a list box.

Private Sub btn_sum_Click()Dim a, n As IntegerDim r As SingleIf check() = False ThenMsgBox ("Required fields are empty")Exit SubEnd IfIf opt_inputbox.Value Thena = InputBox("First Term", "Geometric Progression", 1)r = InputBox("Common Ratio", "Geometric Progression", 1)n = InputBox("How many terms", "Geometric Progression", 1)Elsea = tbox_fn.Textr = tbox_r.Textn = tbox_terms.TextEnd IfDim s As SingleIf r > 1 Thens = (a * ((r ^ n) - 1)) / (r - 1)Elses = (a * (1 - (r ^ n))) / (1 - r)End IfMsgBox ("The sum is " & s)End Sub

Private Sub btn_term_Click()Dim a, n As IntegerDim r As SingleIf check() = False ThenMsgBox ("Required fields are empty")Exit SubEnd IfIf opt_inputbox.Value Thena = InputBox("First Term", "Geometric Progression", 1)r = InputBox("Common Ratio", "Geometric Progression", 1)

34

Page 35: Vb Practical File

n = InputBox("Which Term you want to display", "Geometric Progression", 1)Elsea = tbox_fn.Textr = tbox_r.Textn = tbox_terms.TextEnd IfMsgBox ("The " & n & "th term is " & a * (r ^ (n - 1)))End Sub

Private Sub cmd_Clear_Click()List1.ClearEnd Sub

Private Sub cmd_series_Click()If check() = False ThenMsgBox ("Required fields are empty")Exit SubEnd If

cmd_Clear_ClickDim f, n, terms As IntegerDim r As Singlef = tbox_fn.Textr = tbox_r.Textterms = tbox_terms.TextList1.AddItem "Term" & vbTab & "Value"List1.AddItem "-----------------------"n = 1DoList1.AddItem n & vbTab & f * (r ^ (n - 1))n = n + 1Loop While n <= termsEnd Sub

Function check() As BooleanIf tbox_fn.Text = "" Thencheck = FalseElseIf tbox_r.Text = "" Thencheck = FalseElseIf tbox_terms.Text = "" Then

35

Page 36: Vb Practical File

check = FalseElsecheck = TrueEnd IfEnd Function

36

Page 37: Vb Practical File

Practical – 11

SIMPLE DATABASE SYSTEM: Make a simple database management system using a text file. And the program must check whether the text file is open or not and if the file does not exist, the program prompts the user to create the file by displaying the create button. However, if the file is already there, the program will change the caption of the create button to open file. The program uses Append in the place of Output so that new data will be added to the end of the file instead of overwriting the old data. The program should also show the input box repeatedly so that the user can enter data continuously until he or she enters the word “finish”. Implement error handler to handle errors while reading the file or deleting the file because the program cannot read or delete the file when the file has not been created.

Dim data As String

Private Sub btn_delete_Click()

On Error GoTo error_deleteKill "c:\data\sample.txt"Exit Suberror_delete:MsgBox (Err.Description)End Sub

Private Sub btn_exit_Click()EndEnd Sub

Private Sub btn_open_Click()Open "c:\data\sample.txt" For Append As #1 MsgBox ("File sample.txt opened")Dodata = InputBox("Enter your name\data or type finish to end")If data = "finish" ThenExit DoEnd IfWrite #1, data & vbCrLfMsgBox ("Writing " & data & " to sample.txt ")LoopClose #1

37

Page 38: Vb Practical File

MsgBox ("File sample.txt closed")

End Sub

Private Sub btn_read_Click()tbox_editor.Text = ""

On Error GoTo error_readOpen "c:\data\sample.txt" For Input As #1DoInput #1, datatbox_editor.Text = tbox_editor.Text & data & vbNewLineLoop While Not EOF(1)Close #1

Exit Suberror_read:MsgBox (Err.Description)End Sub

Private Sub Form_Load()data = ""On Error GoTo error_openfileOpen "c:\data\sample.txt" For Input As #1Close #1Exit Sub

error_openfile:MsgBox (Err.Description) & ", please create file", , "Database System"btn_open.Caption = "Create File"

End Sub

38

Page 39: Vb Practical File

39

Page 40: Vb Practical File

Practical – 12

DATA BASE APPLICATION: Create a Database application to handle the database of the students using data control. You should be able to traverse the database to records FIRST, NEXT, PREVIOUS and LAST. Also provide the functionality to ADD, SAVE, EDIT and DELETE the records and EXIT from the program.

Option ExplicitDim prevISBN

Sub ShowButtons() btn_add.Visible = True btn_delete.Visible = True btn_ok.Visible = False btn_cancel.Visible = False Data1.Visible = TrueEnd Sub

Sub HideButtons() btn_add.Visible = False btn_delete.Visible = False btn_ok.Visible = True btn_cancel.Visible = True Data1.Visible = FalseEnd Sub

Private Sub AddBttn_Click() HideButtons prevISBN = Data1.Recordset.Fields("ISBN") Data1.Recordset.AddNewEnd Sub

Private Sub btn_add_Click()HideButtonsEnd Sub

Private Sub btn_cancel_Click() Data1.Refresh Data1.Recordset.FindFirst "Isbn='" & prevISBN & "'" ShowButtons

40

Page 41: Vb Practical File

End Sub

Private Sub btn_delete_Click()On Error Resume Next

Data1.Recordset.Delete If Not Data1.Recordset.EOF Then Data1.Recordset.MoveNext ElseIf Not Data1.Recordset.BOF Then Data1.Recordset.MovePrevious Else MsgBox "This was the last record in the table" End IfEnd Sub

Private Sub btn_first_Click()Data1.Recordset.MoveFirstEnd Sub

Private Sub btn_last_Click()Data1.Recordset.MoveLastEnd Sub

Private Sub btn_next_Click()Data1.Recordset.MoveNextEnd Sub

Private Sub btn_ok_Click()On Error GoTo CancelUpdate

Data1.Recordset.Update Data1.Recordset.MoveLast ShowButtons Exit Sub

CancelUpdate: MsgBox Err.Description Data1.Recordset.CancelUpdate ShowButtons

41

Page 42: Vb Practical File

End Sub

Private Sub btn_prev_Click()Data1.Recordset.MovePreviousEnd Sub

Private Sub Data1_Error(DataErr As Integer, Response As Integer) MsgBox Err.Description Response = 0 Data1.Recordset.CancelUpdateEnd Sub

Private Sub Data1_Validate(Action As Integer, Save As Integer)Dim reply

If tbox_title.DataChanged Or tbox_ISBN.DataChanged Or tbox_Description.DataChanged Or tbox_subject.DataChanged Or tbox_comments.DataChanged Then reply = MsgBox("Record has been changed. Save?", vbYesNo) If reply = vbNo Then Save = False End If End IfEnd Sub

42

Page 43: Vb Practical File

43

Page 44: Vb Practical File

Practical – 13

A DRAWING PROGRAM: Write a program, the user need to fill all the coordinates and choose a color before he can proceed to draw the required shapes like CIRCLE, RECTANGLE etc. If one forgot to fill in the coordinates or choose a color, he will be asked to do so.

Dim Shape As StringDim gpoint As BooleanDim opt As StringDim i As IntegerDim fcolor, pencolor As ColorConstants

Private Sub btn_getPoints_Click()gpoint = TrueEnd Sub

Private Sub btn_Draw_Click()Select Case ShapeCase "circle":If tbox_x1.Text = "" Thentbox_x1.Text = InputBox("Enter x", "Draw", "10")End IfIf tbox_y1.Text = "" Thentbox_y1.Text = InputBox("Enter y", "Draw", "140")End IfIf tbox_radius.Text = "" Thentbox_radius.Text = InputBox("Enter radius", "Draw", "10")End If

Me.Circle (tbox_x1.Text, tbox_y1.Text), tbox_radius.Text, pencolorCase "line":Me.Line (tbox_x1.Text, tbox_y1.Text)-(tbox_x2.Text, tbox_y2.Text) Case "rectangle":

If tbox_x1.Text = "" Thentbox_x1.Text = InputBox("Enter x1", "Draw", "100")End IfIf tbox_y1.Text = "" Then

44

Page 45: Vb Practical File

tbox_y1.Text = InputBox("Enter y1", "Draw", "140")End If

If tbox_x2.Text = "" Thentbox_x2.Text = InputBox("Enter x2", "Draw", "200")End IfIf tbox_y2.Text = "" Thentbox_y2.Text = InputBox("Enter y2", "Draw", "200")End If

Me.Line (tbox_x1.Text, tbox_y1.Text)-(tbox_x2.Text, tbox_y1.Text), pencolorMe.Line (tbox_x1.Text, tbox_y2.Text)-(tbox_x2.Text, tbox_y2.Text), pencolorMe.Line (tbox_x1.Text, tbox_y1.Text)-(tbox_x1.Text, tbox_y2.Text), pencolorMe.Line (tbox_x2.Text, tbox_y1.Text)-(tbox_x2.Text, tbox_y2.Text), pencolor

Case "text":

If tbox_x1.Text = "" Thentbox_x1.Text = InputBox("Enter x", "Draw", "100")End IfIf tbox_y1.Text = "" Thentbox_y1.Text = InputBox("Enter y", "Draw", "140")End If

Set Text = Controls.Add("VB.Label", "DLabel" & i)Text.Left = tbox_x1.TextText.Top = tbox_y1.TextText.ForeColor = pencolorText.Caption = InputBox("Enter Text", "Drawing Text", "Hello")Text.Visible = Truei = i + 1End SelectEnd Sub

Private Sub CFillColor_Click()CommonDialog1.ShowColorMe.FillColor = CommonDialog1.colorEnd Sub

45

Page 46: Vb Practical File

Private Sub CPageColor_Click()CommonDialog1.ShowColorMe.BackColor = CommonDialog1.colorEnd Sub

Private Sub CPenColor_Click()CommonDialog1.ShowColorpencolor = CommonDialog1.colorEnd Sub

Private Sub FClear_Click()Me.ClsEnd Sub

Private Sub FDash_Click()Me.FillStyle = vbDashEnd Sub

Private Sub FDot_Click()Me.FillStyle = vbDotEnd Sub

Private Sub FNone_Click()Me.FillStyle = vbTransparentEnd Sub

Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)StatusBar1.SimpleText = "x = " & X & ", y = " & Y

End Sub

Private Sub Form_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single)

If gpoint ThenSelect Case optCase "fx":

46

Page 47: Vb Practical File

tbox_x1.Text = Xtbox_y1.Text = YCase "sx":tbox_x2.Text = Xtbox_y2.Text = YEnd Select

End If

If Check1.Value = Checked Thenbtn_Draw_ClickEnd If

End Sub

Private Sub Fsolid_Click()Me.FillStyle = vbSolidEnd Sub

Private Sub opt_x1_Click()Option2.Value = Trueopt = "fx"End Sub

Private Sub opt_x2_Click()Option2.Value = Trueopt = "sx"End Sub

Private Sub Option1_Click()gpoint = FalseEnd Sub

Private Sub Option2_Click()gpoint = Trueopt_x1.Value = TrueEnd Sub

Private Sub Scircle_Click()Shape = "circle"

47

Page 48: Vb Practical File

End Sub

Private Sub SLine_Click()Shape = "line"End Sub

Private Sub SRectangle_Click()Shape = "rectangle"End Sub

Private Sub Stext_Click()Shape = "text"End Sub

48

Page 49: Vb Practical File

Practical – 14

A SMART AUDIO PLAYER: Write a program to create a player that enables you to play midi and wave files in your hard drives or floppy A or CDROM. It should allow you to change drives and search for the particular sound file that you wish to play. In this program, you have to add a Combo box, a List Box, a Text Box, a Drive List Box, a command button you label as "PLAY", another command button you label as "STOP", and one more command button you label as "EXIT". You have to add in MMControl and make it invisible.

Dim i As Integer

Private Sub btn_exit_Click()EndEnd SubPrivate Sub btn_Play_Click()If File1.ListCount = 0 Then Exit Sub

Timer1.Enabled = TrueSlider1.Value = 0MMControl1.Command = "Close"MMControl1.Filename = File1.path & "\" & File1.List(i)MMControl1.Command = "Open"MMControl1.Command = "Play"

File1.Selected(i) = Truei = i + 1If i >= File1.ListCount Theni = 0End IfEnd Sub

Private Sub btn_Stop_Click()If btn_Stop.Caption = "Resume" ThenMMControl1.Command = "Play"btn_Stop.Caption = "Pause"ElseMMControl1.Command = "Pause"btn_Stop.Caption = "Resume"

49

Page 50: Vb Practical File

End IfEnd Sub

Private Sub cbox_pattern_Click()If cbox_pattern.ListIndex = 0 ThenFile1.Pattern = "*.wav;*.midi"ElseFile1.Pattern = "*.mp3;*.wav;*.mp4;*.mpeg;*.avi;*.dat"End IfEnd Sub

Private Sub Dir1_Change()File1.path = Dir1.pathEnd Sub

Private Sub Drive1_Change()Dir1.path = Drive1.DriveEnd Sub

Private Sub File1_Click()i = File1.ListIndexbtn_Play_ClickEnd Sub

Private Sub Form_Load()File1.Pattern = "*.midi;*.wav"MMControl1.PlayEnabled = TrueMMControl1.AutoEnable = TrueEnd Sub

Private Sub Timer1_Timer()Slider1.Value = Round(MMControl1.Position / MMControl1.Length * 100)End Sub

50

Page 51: Vb Practical File

51

Page 52: Vb Practical File

Practical – 15

MDI FORM: Write a program to demonstrate the MDI forms application. The parent form contains the menu links to all the above programs and calls them as a child form.

Private Sub AnalogClock_Click()Dim ob As New Clockob.BorderStyle = vbFixedDialogob.Show

End Sub

Private Sub AudioPlayer_Click()Dim ob As New AudioPlayerob.BorderStyle = vbFixedDialogob.Show

End Sub

Private Sub DragDrop_Click()Dim ob As New Drag_Dropob.BorderStyle = vbFixedDialogob.ShowEnd Sub

Private Sub DragDrop2_Click()Dim ob As New draganddrop2ob.BorderStyle = vbFixedDialogob.ShowEnd Sub

Private Sub DynamicControl_Click()Dim ob As New DynamicControlob.BorderStyle = vbFixedDialogob.ShowEnd Sub

Private Sub DynamicMenu_Click()Dim ob As New DynamicMenuob.BorderStyle = vbFixedDialog

52

Page 53: Vb Practical File

ob.ShowEnd Sub

Private Sub GeometricProgression_Click()'Dim ob As New Geometric_Progression'ob.BorderStyle = vbFixedDialog'ob.Show Geometric_Progression.Show 1, MeEnd Sub

Private Sub PCubic_Click()Dim ob As New CubicFunctionob.BorderStyle = vbFixedDialogob.Show

End Sub

Private Sub PDB_app_Click()Dim ob As New DB_Applicationob.BorderStyle = vbFixedDialogob.Show

End Sub

Private Sub PDrawing_Click()Dim ob As New DrawProgob.BorderStyle = vbFixedDialogob.Show

End Sub

Private Sub PictureViewer_Click()Dim ob As New PictureViewerob.BorderStyle = vbFixedDialogob.ShowEnd Sub

Private Sub PIncomeTax_Click()Dim ob As New IncomeTaxob.BorderStyle = vbFixedDialog

53

Page 54: Vb Practical File

ob.Show

End Sub

Private Sub PSDBSystem_Click()Dim ob As New Db_Systemob.BorderStyle = vbFixedDialogob.Show

End Sub

Private Sub ResumeWriter_Click()Dim ob As New ResumeWriterob.BorderStyle = vbFixedDialogob.ShowEnd Sub

Private Sub TicTacToe_Click()Dim ob As New TicTacToeob.BorderStyle = vbFixedDialogob.ShowEnd Sub

Private Sub TraficLight_Click()Dim ob As New Trafic_Lightob.BorderStyle = vbFixedDialogob.ShowEnd Sub

54

Page 55: Vb Practical File

55

Page 56: Vb Practical File

Practical – 16

Develop a program which accepts total taxable income of a person compute income tax as per rules given below:-

The income tax calculation sheet for salaried person isTaxable income Rs. – rate%Up to 110000 – nilUp to 145000 women – nil110000 to 150000 – 10150000 to 250000 – 20250000 to 1000000 – 301000000 upwards – 30*

* a surcharge of 10% of the total tax liability is applicable. Here the total income exceeds rate 1000000.Eduction cess is applicable at the rate 3% on income tax, inclusive of such, age if there is any.

Dim sex As StringPrivate Sub btn_exit_Click()‘Unload MeEndEnd SubPrivate Sub opt_female_Click()sex = "female"End Sub

Private Sub btn_tax_Click()Dim income, tax As Double

income = Val(tbox_income.Text)

tax = 0If income <= 110000 Thentbox_tax.Text = 0Exit SubEnd IfIf income <= 150000 And income > 110000 ThenIf sex = "female" Thentax = (income - 145000) * 0.1Elsetax = (income - 110000) * 0.1End IfElseIf income > 150000 ThenIf sex = "female" Thentax = 500

56

Page 57: Vb Practical File

Elsetax = 4000End IfEnd If

Select Case incomeCase Is <= 250000:income = income - 150000tax = tax + income * 0.2SCase Is <= 1000000:income = income - 250000tax = tax + 20000 + income * 0.3Case Is > 1000000:income = income - 1000000tax = tax + 245000 + income * 0.3tax = tax + tax * 0.1End Select

If chk_edu.Value = Checked Thentax = tax - tax * 0.3End If

tbox_tax.Text = taxEnd SubPrivate Sub opt_male_Click()sex = "male"End Sub

57

Page 58: Vb Practical File

58

Page 59: Vb Practical File

Practical – 1

Consider the following insurance database

59

Page 60: Vb Practical File

Person(driver_id, name,address)Car(regno,model,year)Accident(report_number, date , location)Owns(driver_id,regno)Participated(driver_id,regno,report_number,damage_amount)

Where primary keys are underlined. Firstly create the database tables and populate the tables with the data. Now construct the following SQL queries for this relational database.

create table person(driver_id int primary key identity,name varchar(30),address varchar(200));

create table car(regno varchar(10) primary key ,model varchar(50),year int);

create table accident(report_number varchar(10) primary key,date smalldatetime,location varchar(30));

create table owns(driver_id int references person(driver_id),regno varchar(10) references car(regno));

create table participated(driver_id int references person(driver_id),regno varchar(10) references car(regno),report_number varchar(10) references accident(report_number),demage_amount numeric(8,2)constraint pk_participated primary key(driver_id,regno,report_number));

60

Page 61: Vb Practical File

a.) Find the total number of people who owned cars that were involved in accidents in a particular year (say year 2000).

select count(distinct participated.driver_Id) from accident, owns, participated where year(accident.Date) ='2009' and accident.report_Number=participated.report_Number and participated.regNo=owns.regNo and owns.driver_Id=participated.driver_Id;

b.) Add a new accident to the database; assume any values for required attributes.

insert into accident(report_number,date,location) values('AR006','11/20/2009','Karnal')insert into participated values(3,'HR07B 6010','AR006',2500)

c.) Delete the particular car model (say Honda i20) belonging to a particular person ( say Ram).

delete from car where model='ZEN' and regno in (select regno from owns where driver_id=(select driver_id from person where name='Arun Singh'))ordelete from car where model='ZEN' and regno in (select regno from person,owns where person.name = ’Arun Singh’ and person.driver_id = owns.driver_id)

d.) Find the number of accidents in which the cars belonging to a particular person (say Ram) were involved.

select count(*) from accident where exists(select * from participated,person where participated.driver_id=person.driver_id and person.name='Arun Singh' and accident.report_number = participated.report_number)

e.) Update the damage amount for the car with particular license number (say HR20 B2020) in the accident with particular report number (say AR2179) to Rs. 10000/-.

update participated set damage_Amount = 10000 where report_Number = 'AR002' and regNo = 'HR07B 6010';

Practical – 2

Consider the following employee database

61

Page 62: Vb Practical File

Employee(fname,mname,lname,eno,dob,address,salary,supno,deptnum)Department(deptname,deptnum,mgreno,mgrstartdate)Departmentlocation(deptnum, deptloc)Works-ON(eno,pno,hours)Project(pname, pno, ploc,deptnum)Dependent(eno, dependentname,dob,relationship).

Where primary keys are underlined. Firstly create the database tables and populate the tables with the data. Now construct the following SQL queries for this relational database.

create table department(deptnum int primary key,deptname varchar(20) unique,mgreno int,mgrstartdate smalldatetime);

create table employee(eno int primary key,fname varchar(20),mname varchar(20),lname varchar(20),dob smalldatetime,address varchar(200),salary numeric(8,2),supno int,deptnum int foreign key references department(deptnum));

create table departmentlocation(deptnum int foreign key references department(deptnum),deptloc varchar(20),primary key(deptnum,deptloc));

create table project(pno int primary key identity,pname varchar(20),ploc varchar(20),deptnum int foreign key references department(deptnum));

62

Page 63: Vb Practical File

create table works_on(eno int foreign key references employee(eno),pno int foreign key references project(pno),hours numeric(3,1)primary key (eno,pno));

create table dependent(eno int foreign key references employee(eno),deptname varchar(30),dob smalldatetime,relationship varchar(20)primary key(eno,dependentname));

a.) Retrieve the names of employees in the department (say 5) who works for more than 10 hrs for the project name.

Select fname from employee where eno in (select eno from works_on where pno in(select pno from project where hours>10 and deptnum=5));

b.) Find the names of employees who are directly supervised by supervisor (say Neetu).

Select fname from employee where supno in (select eno from employee where fname='neethu');

c.) Retrieve the names of employee who work on every project controlled by a department (say deptno=5).

select fname, lname from employee where not exists (select * from works_on w where (w.pno IN (select pno from project WHERE Deptnum = 5)) AND NOT EXISTS (select * from works_on x where x.eno = employee.eno AND x.PNO = w.PNO));

d.) Retrieve the names of each employee who has a dependent with the same first name of employee.

Select fname , lname as 'Name' from employee where eno in (select eno from dependent where fname=deptname);

e.) Retrieve the name of each employ who have no dependents.

63

Page 64: Vb Practical File

Select fname,lname from employee where NOT EXISTS(select * from dependent where employee.eno=dependent.eno);

f.) Retrieve the name of each employ who work on the projects say 1,2,3

Select distinct works_on.eno, fname from works_on,employee where pno in(1,2,3) and works_on.eno=employee.eno;

Practical – 3

Consider the following database maintained by a book dealer

64

Page 65: Vb Practical File

Author(authorid,name,city,country)Publisher(publisherid,name,city,country)Catalog(bookid, title,authorid, publisherid, categoryid, year,price)

Category(categoryid, description)Orderdetails(orderno, bookid, quantity)

Create the above tables properly by specifying the primary keys and foreign keys.Enter altleast 4 to 5 tuples for each table.

Now construct the following SQL queries for this relational database.

create table author(authorid int primary key,name varchar(30),city varchar(30),country varchar(30));

create table publisher(publisherid int primary key,name varchar(30),city varchar(30),country varchar(30));

create table catalogs(bookid int primary key,title varchar(20),authorid int,publisherid int,categoryid int,year int,price numeric(8,2)foreign key(authorid) references author(authorid),foreign key (publisherid) references publisher(publisherid),foreign key(categoryid) references category(categoryid));

create table category(categoryid int primary key,description varchar(20));

65

Page 66: Vb Practical File

create table orderdetails(orderno int primary key,bookid int references catalogs(bookid),quantity int);

a) Give the details of the author who have two or more books in the catalog and the price of the books is greater than the average price of the books in the catalog and the year of publication is after 2000.

select clog.Authorid,A.name from Catalogs clog,Author A where A.Authorid=Clog.Authorid and Clog.Year > 2000 and Clog.Price >(Select Avg(Price)from Catalogs) group by clog.Authorid,A.name having count(clog.Authorid)>=2

b) Find the author of the book which has maximum sales.

create view salesdetails as(Select OD.Bookid as Book#,C.Price as Cost,Sum(OD.quantity) as Qty,sum(OD.quantity*C.price) as salesfrom Orderdetails OD,Catalogs C,Author Awhere OD.Bookid=C.Bookid and C.Authorid=A.Authoridgroup by OD.Bookid,C.Price);

select A.Authorid,A.name,S.Book#,S.Salesfrom Author A,Catalogs C,Salesdetails Swhere A.Authorid=C.Authorid and S.Book#=C.Bookid and sales=(select Max(Sales) from Salesdetails);

c) Give the details of the top 5 authors who have published maximum number of books.

create view booksnum as(select count(*) as nbooks,authorid from catalogs group by authorid )select author.authorid,author.name,author.city,author.country from author where authorid in (select top 5 authorid from booksnum order by nbooks desc)

d) Give the details of the author who have published books of a particular category (say Economics).

select author.authorid,author.name,author.city,author.country from author,catalogs,category where description='Economics' and category.categoryid=catalogs.categoryid and author.authorid=catalogs.authorid

Practical – 4

66

Page 67: Vb Practical File

Consider the following database Employee(empno,name,office,age)Books(isbn, title,authors,publisher)Loan(empno,isbn,date)

Now construct the following SQL queries for this relational database.

create table employee(empno int primary key,name varchar(30),office varchar(20),age int);create table books(isbn int primary key,title varchar(30),authors varchar(20),publisher varchar(30));create table loan(empno int references employee(empno),isbn int references books(isbn) ,date smalldatetime);

a.) Find the names of the employee who have borrowed a book published by a particular publisher (say McGraw-Hill).

select name from employee,books,loan where publisher='McGraw-Hill' and books.isbn=loan.isbn and loan.isbn=employee.empno

b.) Find the names of employee who have borrowed all the books published by a particular publisher( say McGraw-Hill)

select name from employee e join loan l on e.empno=l.empno join (select isbn from books where authors = 'Smith') x on l.isbn=x.isbngroup by e.empno,namehaving count(*)=(select count(*) from books where authors = 'Smith')

c.) Find the names of employees who have borrowed more than five different books published by a particular publisher( say McGraw-Hill)

select name from employee,loan where employee.empno=loan.empno and isbn in ( select distinct isbn from books where publisher='McGraw-Hill') group by employee.empno,name having count(isbn) >=5

67

Page 68: Vb Practical File

d.) For each publisher, find the names of employees who have borrowed more than five books of that publisher.

select name from employee,loan,books where employee.empno=loan.empno and books.isbn=loan.isbn group by employee.empno,name,books.publisher having count(loan.isbn) >=5

Practical – 5

Consider the following database which stores the student and course information

68

Page 69: Vb Practical File

Student(name,student_id,class,major)Course(course_name,course_id,credit_hours,department)Section(section_id, course_id,Semester,year,instructor)Grade_report(student_id,section_id,grade)Prerequisite(course_id,prerequisite_number)

Now construct the following queries in SQL on the database tablescreate table student(student_id int primary key,name varchar(20),class varchar(20),major varchar(20));

create table course(course_id varchar(20) primary key,course_name varchar(30),credit_hours int,department varchar(20));

create table section(section_id int,course_id varchar(20),semester int,year int,instructor varchar(30),primary key(section_id),foreign key (course_id) references course(course_id));create table grade_report(student_id int,section_id int,grade varchar(10)primary key(section_id,student_id),foreign key (student_id) references student(student_id),foreign key (section_id) references section(section_id));

create table prerequisite(course_id varchar(20) references course(course_id),prerequisite_number varchar(20) references course(course_id),primary key (course_id,prerequisite_number)

69

Page 70: Vb Practical File

);

a.) Retrieve the names of all senior students majoring in CS.

select * from student where major='CS'

b.) Retrieve the name of all courses taught by particular instructor (say Dr. Rajender Nath) in particular year (say 2010).

select course_name from course,section where course.course_id=section.course_id and year=2010 and instructor='Dr. Rajendar Nath'

c.) For each section taught by particular instructor (say Dr. Rajender Nath) retrieve the course_id, semester, year, and number of students who took the section.

select section.course_id,semester,year, count(*) from course,section where course.course_id=section.course_id and instructor='Dr. Rajendar Nath' group by section_id

d.) Retrieve the name and major departments of all straight A students (students who have a grade of A in all their courses).

select name,major,department from student,course,grade_report,section where student.student_id=grade_report.student_id and section.section_id=grade_report.section_id and course.course_id=section.course_id and grade='A'

e.) Retrieve the names and major department of all students who do not have a grade of A in any of their courses.

select name,major,department from student,course,grade_report,section where student.student_id=grade_report.student_id and section.section_id=grade_report.section_id and course.course_id=section.course_id and grade <> 'A'

70