Page 49 - Open Soource Technologies 304.indd
P. 49

Unit 3: Understanding Controls and Control Events



               We want to display some text, say, "Welcome to TextBoxes", in TextBox1 when the Button is
               clicked. The code looks like this:

                 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e_
                 As System.EventArgs) Handles Button1.Click
                 TextBox1.Text = "Welcome to TextBoxes"
                 End Sub

               Code to Work with PassWord Character

               Set the PasswordChar property of TextBox2 to *. Setting that will make the text entered in
               TextBox2 to be displayed as *. We want to display what is entered in TextBox2 in TextBox1. The
               code for that looks like this:
                 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e_
                 As System.EventArgs) Handles Button1.Click
                 TextBox1.Text = TextBox2.Text
                 End Sub

               When you run the program and enter some text in TextBox2, text will be displayed as *. When
               you click the Button, the text you entered in TextBox2 will be displayed as plain text in TextBox1.
               Code to Validate User Input
               We can make sure that a TextBox can accept only characters or numbers which can restrict
               accidental operations. For example, adding two numbers of the form 27+2J cannot return
               anything. To avoid such kind of operations we use the KeyPress event of the TextBox.
               Code that allows you to enter only double digits in a TextBox looks like this:

                 Private Sub TextBox1_KeyPress(ByVal sender As Object,ByVal e As_
                 System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
                 If(e.KeyChar < "10" Or e.KeyChar > "100") Then
                 MessageBox.Show("Enter Double Digits")
                 End If
                 End Sub

               Creating a TextBox in Code

                 Public Class Form1 Inherits System.Windows.Forms.Form
                 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As_
                 System.EventArgs) Handles MyBase.Load
                 Dim TextBox1 as New TextBox()
                 TextBox1.Text="Hello Mate"
                 TextBox1.Location=New Point(100,50)
                 TextBox1.Size=New Size(75,23)
                 Me.Controls.Add(TextBox1)
                 End Sub
                 End Class



                                      LOVELY PROFESSIONAL UNIVERSITY                         43
   44   45   46   47   48   49   50   51   52   53   54