1 / 37

Creating Custom Controls

Creating Custom Controls. Overriding ToString Method. Every class you create in VB.Net is derived from a built-in class named object. Mscorlib/system/object The object class has a method named ToString method which returns a fully-qualified class name. This method is overridable.

Download Presentation

Creating Custom Controls

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Creating Custom Controls

  2. Overriding ToString Method • Every class you create in VB.Net is derived from a built-in class named object. • Mscorlib/system/object • The object class has a method named ToString method which returns a fully-qualified class name. • This method is overridable.

  3. Code Example Public Class Person Public SSN As String Public FirstName As String Public LastName As String Public BirthDate As Date Public Overrides Function ToString() As String toString = FirstName & " " & LastName & "'s birthday is " & BirthDate.ToString End Function

  4. Overriding and Overloading GetHashCode Method Public Overloads Overrides Function GetHashCode() As Integer GetHashCode = CInt(SSN.Substring(0, 3)) Mod 10 End Function Public Overloads Function GetHashCode(ByVal M As Integer) As Integer GetHashCode = CInt(SSN.Substring(0, 3)) Mod M End Function Code Example: Dim myPerson As New Person() myPerson.SSN = TextBox1.Text TextBox2.Text = myPerson.GetHashCode TextBox3.Text = myPerson.GetHashCode(100)

  5. Exception • Exceptions signal errors or unexpected events that occur while an application is running. • An error handler is a section of code that intercepts and responds to exceptions.

  6. Structured Error Handling Try result = Val(TextBox1.Text) / Val(TextBox2.Text) TextBox3.Text = result.ToString Catch except As InvalidCastException MessageBox.Show(except.Message) Catch except As DivideByZeroException MessageBox.Show(except.Message) Catch except As Exception 'Handle everything else MessageBox.Show(except.Message) Finally MessageBox.Show("I get exdecuted, no matter what") End Try

  7. Catch • Catch ExceptionVar As ExceptionType • VB.Net Help provides information about a method’s exceptions. • Try • fileNumber = FreeFile() • FileOpen(fileNumber, "c:\stdata.txt", OpenMode.Input) • Catch err As FileNotFoundException • MessageBox.Show(err.Message) • MessageBox.Show("file not found") • Catch err As NotSupportedException • MessageBox.Show(err.Message) • End Try

  8. User-Defined Application Exceptions • System.ApplicationException • Throw • Code example: • Try • 'statements • Throw New ApplicationException("Test exception") • Catch err As ApplicationException • MessageBox.Show(err.Message) • End Try

  9. User-Defined Exception Class Public Class JobCodeException Inherits System.ApplicationException Sub New(ByVal strMessage As String) MyBase.New(strMessage) End Sub End Class

  10. Using User-Defined Exception in Class Private hiddenJobCode As Long Public Property JobCode() Set(ByVal Value) If Value < 1 Or Value > 4 Then Throw New JobCodeException("Invalide JobCode") Else hiddenJobCode = Value End If End Set Get JobCode = hiddenJobCode End Get

  11. Using User-Defined Exception in Program Dim myEmp As New Emp() Try myEmp.Eid = TextBox1.Text myEmp.Ename = TextBox2.Text myEmp.salary = CDbl(TextBox3.Text) myEmp.JobCode = TextBox4.Text Catch err As JobCodeException MessageBox.Show(err.Message) TextBox4.Focus() TextBox4.SelectAll() End Try

  12. Creating Custom Controls • A customer control is a control that is designed by a programmer for a specific purpose. It is derived from the System.Windows.Forms.UserControls class. • Two ways to create a control: • Windows Control Library Project • Controls can be used in multiple projects. • Add a new UserControl to an existing project. • Only in current project

  13. Creating TimeZone Control • This control displays time in each time zone. It exposes a Zone property and a ShowTime method. • New Project/Windows Control Library • Design control’s appearance and add any functionality you want. • Build the DLL: • The DLL is saved in project’s Bin folder. • Create a Windows project to test the control. • Right Click Windows tab of the Tool Box and choose Customize ToolBox • Click .Net Framework component • Click Browse to select the DLL

  14. TimeZone Control Code Public Class TimeZone Inherits System.Windows.Forms.UserControl Enum tzone Eastern = 1 Central Mountain Pacific End Enum Private sysTime As Date Private tmZone As tzone Public Property Zone() As tzone Get Zone = tmzone End Get Set(ByVal Value As tzone) tmzone = Value End Set End Property

  15. Private Sub TimeZone_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load tmZone = tzone.Eastern End Sub Public Sub ShowTime() sysTime = Now If tmZone = tzone.Eastern Then lblE.Text = sysTime.ToLongTimeString lblC.Text = DateAdd(DateInterval.Hour, -1, sysTime).ToLongTimeString lblM.Text = DateAdd(DateInterval.Hour, -2, sysTime).ToLongTimeString lblP.Text = DateAdd(DateInterval.Hour, -3, sysTime).ToLongTimeString ElseIf tmZone = tzone.Central Then lblC.Text = sysTime.ToLongTimeString lblE.Text = DateAdd(DateInterval.Hour, 1, sysTime).ToLongTimeString lblM.Text = DateAdd(DateInterval.Hour, -1, sysTime).ToLongTimeString lblP.Text = DateAdd(DateInterval.Hour, -2, sysTime).ToLongTimeString ElseIf tmZone = tzone.Mountain Then lblM.Text = sysTime.ToLongTimeString lblE.Text = DateAdd(DateInterval.Hour, 2, sysTime).ToLongTimeString lblC.Text = DateAdd(DateInterval.Hour, 1, sysTime).ToLongTimeString lblP.Text = DateAdd(DateInterval.Hour, -1, sysTime).ToLongTimeString Else lblP.Text = sysTime.ToLongTimeString lblE.Text = DateAdd(DateInterval.Hour, 3, sysTime).ToLongTimeString lblC.Text = DateAdd(DateInterval.Hour, 2, sysTime).ToLongTimeString lblM.Text = DateAdd(DateInterval.Hour, 1, sysTime).ToLongTimeString End If End Sub End Class

  16. Code Using TimeZone Control Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click TimeZone1.Zone = TimeZoneControlLibrary.TimeZone.tzone.Pacific TimeZone1.ShowTime() End Sub

  17. Create an Inherited User Control • Create a user control from an existing control such as TextBox, Label, etc. • Example: Create a control, called ValidDate, that looks exactly like a textbox, but it will validate the entry for a valid date. • Inherits from System.Windows.Forms.TextBox • Properties: MaximumDate, MinimumDate with default value • Event: InvalidDate event

  18. ValidDate Control Code Public Class ValidDate Inherits System.Windows.Forms.TextBox Public Event InvalidDate(ByVal message As String) Private maxDate As Date = Now.Date.AddYears(1) Private minDate As Date = Now.Date Public Property MaximumDate() As Date Get MaximumDate = maxDate End Get Set(ByVal Value As Date) maxDate = Value End Set End Property Public Property MinimumDate() As Date Get MinimumDate = minDate End Get Set(ByVal Value As Date) minDate = Value End Set End Property

  19. Private Sub ValidDate_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Validating If Not IsDate(Me.Text) Then Me.SelectAll() e.Cancel = True RaiseEvent InvalidDate("Date not valid") Else Dim enteredDate As Date = CDate(Me.Text) If enteredDate < minDate Or enteredDate > maxDate Then RaiseEvent InvalidDate("Date out of range") Me.SelectAll() e.Cancel = True End If End If End Sub End Class

  20. Using DateTime Picker • Properties: • MaxDate • MinDate • Value • One year appointment: • DateTimePicker1.MaxDate = DateAdd(DateInterval.Year, 1, Now) • DateTimePicker1.MinDate = Now • Event: • ValueChanged

  21. Create an One-Year Appointment Date/Time Picker Control • This control contains a DataTimePicker to choose appointment date up to one year in advance, and buttons to choose time. This control exposes two properties: • SelDate • SelTime

  22. Creating Form Controls With Code • Use the name space: System.Windows.Forms • Ex. Define a textbox: • Dim tryTxt As New System.Windows.Forms.TextBox() • Set property value: • tryTxt.Location = New System.Drawing.Point(70, 70) • tryTxt.Size = New System.Drawing.Size(144, 20) • Add to form’s Controls collection: • Me.Controls.Add(tryTxt) • Form Controls example: • Dim o As Object • For Each o In Me.Controls • MessageBox.Show(o.GetType.ToString) • Next

  23. Graphics Basics • Create a graphics object. • Create a Pen or Brush object to draw with. • Call the drawing methods from the Graphics object to draw.

  24. Form’s Paint Event • Each time a form is displayed, resized, moved, maximized, restored, the form’s Paint event is triggered. • Use the Paint event’s EventArg or a form’s CreateGraphics method to create a graphics object. • Objects: Point, Size, Shape

  25. Graphics Example Private Sub Form2_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint Dim penBlk As New Pen(Color.Black, 10) Dim gr As Graphics = e.Graphics gr.DrawRectangle(penBlk, 50, 50, 100, 20) Dim gr1 As Graphics gr1 = Me.CreateGraphics Dim penRed As New Pen(Color.Red, 10) Dim startPoint As New Point(70, 10) Dim grSize As New Size(50, 20) Dim shapeRect As New Rectangle(startPoint, grSize) gr1.DrawRectangle(penRed, shapeRect) End Sub

  26. Creating an Array of Objects Dim emps(2) As emp Dim i As Integer For i = 0 To emps.GetUpperBound(0) emps(i) = New emp() Next emps(0).Eid = "e1" emps(0).Ename = "peter" emps(0).salary = 5000

  27. Creating an Array of Textbox with Code Dim test(1) As System.Windows.Forms.TextBox Dim pointX As Integer = 50 Dim pointY As Integer = 80 Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim i As Integer For i = 0 To 1 test(i) = New System.Windows.Forms.TextBox() test(i).Location = New System.Drawing.Point(pointX, pointY) test(i).Name = "TextBox" & i.ToString test(i).Size = New System.Drawing.Size(144, 20) test(i).Text = test(i).Name test(i).Visible = True pointY += 50 Me.Controls.Add(test(i)) Next End Sub

  28. Creating a MyGrid Control • Properties: • Rows, Cols • Cell • Methods: • AddRow • ReDimension

  29. Assemblies • An assembly is a logical grouping of functionality into a physical file. One or many business logic components can be reside in an assembly. • This collection of components is compiled into a .DLL file. • We can import this .DLL component to any VB projects.

  30. Steps to Create An Assembly • Create a class library with classes. • You can also use existing classes by Project/Add Existing Item • Select Build/Build Solution to compile the code. • When the class library is compiled successfully, an assembly is created and stored in the project’s Bin folder. • Demo: CustomerBackGroundCheck

  31. Using the Assembly • Reference the assembly: Project/Add Reference and use the Browse button to select the assembly. • Import the assembly.

  32. Code Using Assembly Imports CustomerBackGroundCheck Public Class Form1 Dim test As New CustomerBackGroundCheck.BackGroundCheck() Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load If test.CreditCheck("C1") = "good" Then MessageBox.Show("good credit") Else MessageBox.Show("bad credit") End If End Sub

  33. Adding Events to Controls Created with Code • AddHandler object.event, AddressOfeventhandler

  34. Private pButton(2) As Windows.Forms.Button Private pointX As Integer = 0 Private pointY As Integer = 0 Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim I As Integer For i = 0 To 2 pButton(i) = New System.Windows.Forms.Button() pButton(i).Location = New System.Drawing.Point(pointX, pointY) pButton(i).Name = "button" & i.ToString pButton(i).Size = New System.Drawing.Size(15, 20) pButton(i).Text = i.ToString Me.Controls.Add(pButton(i)) AddHandler pButton(i).Click, AddressOf ButtonClickHandler pointY += 20 Next End Sub Public Sub ButtonClickHandler(ByVal sender As Object, ByVal e As _ System.EventArgs) MessageBox.Show(sender.name) End Sub

  35. Testing Custom Controls • Create and build the control. • Keep the custom control project open, and go to Windows desktop to open a second Visual Studio window. • In the second Visual Studio window, open a project to test the custom control.

  36. Using One Event Handler to Handle Events Generated by Many Controls • Assume we have 3 buttons. • Use the Handles clause in the event procedure to associate controls with the event procedure. • We can assign a value for each control’s Tag property, or use control’s TabIndex property to determine which control generates the event.

  37. Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click, Button2.Click, Button3.Click If sender.tag = "1" Then MessageBox.Show("button 1 clicked") ElseIf sender.tag = "2" Then MessageBox.Show("button 2 clicked") Else MessageBox.Show("button 3 clicked") End If End Sub Note: VB IntelliSense will not show the Tag property after you type sender.

More Related