Wednesday 2 June 2010

Using Dialog Result

If you are asking the user to confirm or cancel details, say you have a validation check on a textbox for instance, which is a system check to confirm the correct syntax etc is correct, for instance a phone number entered is in the format XXXX XXX XXXX. Now you want to display a message box asking the user to confirm that the number, say 0123 456 7890 is correct, i.e.is this the number you meant to put in?

Do you see the two checks here?:

System check for correct format
User check of actual number entered

No point in doing this the other way round if you see what I mean? That is, ask user to confirm number and then validate the format of it. If the format is wrong then the user input will be wrong anyway, they might have put in a letter instead of a number for instance.

It might be an idea to start a simple VB project with a form and a text box if you don't already have one.Start up your new project as below. Call it anything you want, DialogTest or TestDialog, anything.



So you want to finally ask the user if this is the correct value they have put in before they move on. It can be a pain to be asked these things but many do not understand how useful this type of "interruption" is! It can save so many problems later on down the road.

Put a button and textbox on your form as below:



Now to open your code window while selecting the correct event for the button press action simply double-click the button on the form design. Each control (Button, text box etc) has a default event, in this case the button has a default event ButtonClick. Once you double click you should see something like this in yourcode window:


Note that I have put an underscore at the end of top line on the event handler (The bit between private sub and end sub) and cut the rest of the line down under the top line to see the whole event details. Yours will be all in one line but you can do this too so that it looks neater and you can read it in one screen.

Now declare a variable of type integer. Integer because it will be holding whole numbers like 5, 6, 7 etc Call it what you like but in this case you could use MsgAnswer or similar. Declare it within the button click event as shown:



You will get a squiggly line under the variable or any variable you are not yet using, this doesn't mean an error it just means the variable is unused as of this point.

Now Add a small statement to show a message box (when button is clicked) asking the user if the value they put in the text box is correct. Code like this:

MessageBox.Show("Is the value " & txt1.Text & "  Correct")

Note: your textbox (txt1) may have a different name property so be sure to change that or you will get an error message by copying this line. Default is usually Text1. So if you have not changed it's name in the properties list you would instead put:

MessageBox.Show("Is the value " & Text1.Text & "  Correct")

Can you see the difference?


You can see the final code below for this part of the excercise:



Run this code using the F5 button just to get a feel for what is happening so far. Put in a name and press the button. You will get a small message box with an OK button asking Is the value Correct?

At this point you only have an Ok button, but you want to have a cancel and OK button. To do this got to the end of the line of code in the messagebox and put two commas, with a string value after the first one as below:

MessageBox.Show("Is the value " & Text1.Text & "  Correct",  "User Check Value", ) 

After the last comma press the space bar and you should see a list of different options pop up. Pick MessageBoxButtons.OKCancel

If the user is happy with the value they have entered then you do not want to do anything, otherwise highlight the text so they can easily fix the value. proceed to assign the messagebox value to the variable you declared. The messagebox returns an integer value depending on the option picked (Yes/Cancel).

so your code will now look like:

MsgAnswer = MessageBox.Show("Is the value " & txt1.Text & "  Correct", "User Check Value", MessageBoxButtons.OKCancel)

And also add this IF statement:

If MsgAnswer = Windows.Forms.DialogResult.Cancel Then
            txt1.Focus() '
Sets focus to the text box
            txt1.SelectionStart = 0 '
Sets the selection to the start of the text box
            txt1.SelectionLength = txt1.Text.Length ' Selects the length = to the length of the text in the box
End If

So now if you run it you will see that if you press cancel on the message box it will highlight the text in the textbox and you can enter a new value. If you say OK it will not do anything.

This was just a simple exercise to show you how the messagebox value returned from user interaction can be use to do something else depending on the answer returned. As you are probably aware the scope of this is much larger than use it has been put to in this example.

Thursday 4 March 2010

Using the IIF Statement


For those that aren't aware the definition 'IIF' may seem like a spelling mistake but VB uses a statement called the IIF statement to compare an input and return either of two values. It is, in effect, a shorthand was of doing:

If Value = condition THEN 
  Do Something here

ELSE
  Do something else
END IF

It is generally used for assigning values to variables or calling another routine rather than processing large pieces of code. The terminology is:

IIF(Input = (Value), Dothis, ElseDoThis)

And you can asign the value to something like on a form. So for example in VB create a form with a 2 text boxs and a label as below:



Text box 1 is the left box. The second text box is to give something you can tab to and fire the validate event.

On the form right click and pick view code. In the code window from the left drop down box you will see the text box name, pick this then in the right hand drop down list pick the event Validating. You will now see the following:




In this event put the following code:

lbl1.Text = IIf(txt1.Text = "Y", "Answer is Yes.", "Answer is no.")

Remember your label and textbox are usually called 'label1' etc but you can change this too what you prefer, I use lbl1 and txt1 as they are shorter to type. 

So with this code you are assigning to the label whatever the IIF statement evaluates every time you tab from the first text box to the next.

If you enter 'Y' the label will get assigned a string of text "Answer is Yes.", any other value and the label will get assigned to it the value "Answer is No."

Save your design and then run it. Put 'Y' in the box and then tab to the next text box and watch what gets put in the label.

If you want to make sure that an upper case 'Y' always gets put in, even if the input is a small case 'y' then you can do use the upper case function in the code:

lbl1.Text = (IIf(UCase(txt1.Text) = "Y", "Answer is Yes.", "Answer is no."))

This just means that anything you put in the textbox will be changed to upper case. This will then handle a user putting in both upper case and lower case 'Y' and 'N'.

Some other things you can do is go to the first text box's properties and change the maxlength value from 32k to 1. This will mean you can only put in a single value. This will help us as we do not need to code as much to check that only a single character value has been put in. As below, look at the highlighted portion in the properties window, bottom right:



Now you may wonder if there is an easier way of doing this rather than having a second text box to allow validating, which then runs the code because the code is in the validate event handler. Validating only works when you are exiting a control such as a text box so to run your code without having to leave the text box you can use the textChanged event instead of the validating event. You can see the code in the new event handler below:




If you are unsure how to pick a certain event then see here for picking from the drop down lists in the code window. Example shows picking form load event but the principle is the same. You pick the control from the left drop down and then the associated event from the right drop down, have a look at the screen shots to see how in the link. You can also delete the second text box as there's no need for it now.

Now that we have our code in the new event we want to try it out so save the project and then run it. Notice how only a 'y' or a  'Y' changes the answer to "Answer is Yes"?




Tuesday 9 February 2010

Using Functions

In this post I am going to explain the fundamentals of a function in your code, how to pass parameters in the function and return values back to the calling code.

So you might have a bit of code where in part of that code you might want to check a certain condition before you continue, and to do this you may need to go to another class etc to check this. So you may have the following in a click button event for checking a name exists:


Dim fName as string ' Declare variable

fName = firstNameInput.text  ' Whatever the first name value is will be assigned to the fName variable for use in the function
Dim sName as String ' Declare variable
sName = surNameInput.text ' Whatever the last name value is will be assigned to the sName variable for use in the function
Dim Variable As String ' Declare variable
vCheckName = txtBox1.text Whatever is typed (Y/N) in the text box is then assigned to the variable

If vCheckName= "Y" Then ' When you click the button this will check if Y/N is put in the text box and call function

    If  Person.CallNameCheck(fName, sName) = True Then  ' Call this function with the variable values passed as the parameters to use to check if the person exists etc
         ' Do something
    Else
        ' Do something else
    End If
End If


Notice the code above saying:

Person.CallNameCheck(fName, sName) = True

In the Person class, which is where the function is you will find something like this:


Function CallNameCheck(varFName as String, varLName as string) As Boolean


' Code to gather information and check name goes in function and uses function parameters passed
' What would generally happen here is that the data where the names reside (DB or collection)
' would be gathered and looped through. If there was a name matching the one passed through
' the parameters of the function then something like a number count would be incremented
' and an If statement would determine if that number was more than 0 then True would be returned
' The if statement would be something like as follows:

If Count = 1 then
  CallNameCheck = True
Else
  CallNameCheck = False
End If

This would then return true or false to the original condition i.e. This part:


If vCheckName= "Y" Then '

    If  Person.CallNameCheck(fName, sName) = True Then  ' Check if True or False
         ' Do something if True is returned
    Else
        ' Do something else if False is returned
    End If
End If

If it was false then the code would go to the 'Else' statement, do whatever it has to do then exit out of the final IF statement.

This is basically what you use a function for.

Note: a function returns a certain value (True/False in this instance) to the calling statement whereas a procedure does not.

And also note that the function's parameter names can and usually do differ in the actual function itself to that, which is passed from the calling code. So in this case:

fName = varFName
sName = varLName

 It is simply because the variables used in the calling code use different named variables than that to the code where the function resides. These values (varFName, varLName) would maybe be used to be passed to a database procedure which would run and check the names against the values you passed.



Tuesday 26 January 2010

Using Check Boxes

A check box is a simple control that allows the user to tick a box to mean they want a certain action performed. It is similar to thinking either true or false, or 1 or 0, and is actually used in this fashion in programming techniques.

When a checkbox is checked its CheckState property is set to 1 and when unchecked to 0.

If you want to have some code run when the checkbox CheckState is changed then you can use the following event:

CheckBox1_CheckStateChanged event.

In this event you can code for both a 1 and 0 event (Checked and Unchecked).

The CheckStateChanged event does not know itself what value the checkbox is at. all it knows is that it has changed. You have to read the properties of the checkbox to find that out. So if you wanted to do something depending on the state of the Checkbox (1, 0) you would maybe have an IF statement saying:

Note comments follow a single quote (')
---------------------------------------------------------
If CheckBox1.CheckState = 1 Then  ' Meaning it has been ticked
  'do something such as run a procedure or function etc
Else ' Can only mean the checkstate is otherwise 0
 ' Do some other operation
End If
---------------------------------------------------------

This code woul be in the CheckStateChanged event handler meaning that whenever the check state changes run the code inside the event handler. The full code is below:

Private Sub CheckBox1_CheckStateChanged(ByVal sender As Object, _
    ByVal e As System.EventArgs) Handles CheckBox1.CheckStateChanged

        
       If CheckBox1.CheckState = 1 Then  ' Meaning it has been ticked

           'do something such as run a procedure or function etc
      Else ' Can only mean the checkstate is otherwise 0

          ' Do some other operation
      End If
End Sub

Note:

Instead of using CheckBox1.CheckState = 1 you can also use:


CheckBox1.CheckState = CheckState.Checked

For 0 you can use:
  
CheckBox1.CheckState = CheckState.Unchecked

Which is the same as:
  
CheckBox1.CheckState = 0



This may seem slightly confusing and a pointless thing to have different notation meaning the same thing but it is essential to learn that these things exist in all code, and you have to learn how to spot them and understand what they mean.

Setting a Different Mouse Pointer

To use different mouse pointers such as a hand or a cross-hair when the cursor is moved over a control (Button for example) you simply set the Cursor property of the control that you want to see a different pointer on. So if you wanted to see a hand pointer on a button you would set the button's Cursor property and pick the pointer that you want to see when the mouse cursor is over that control.

Some designers like to do this as it gives a visual indication to the user that you can press the button, and when you move the cursor off the button it goes back to a simple pointer.

The default setting is a pointer on the form and on all the controls.

You can also set it programmatically by using the mouse enter event handler on a control such as a button as follows:

---------------------------------------------------------------
Private Sub btn2_MouseEnter(ByVal sender As Object, _
    ByVal e As System.EventArgs) Handles btn2.MouseEnter
        btn2.Cursor = Cursors.Hand
    End Sub
---------------------------------------------------------------

Pick the button from the drop down list at the top left in your code window and it will automatically populate the non-bold code above into your code editor window. You then put the code in, shown in bold above.

Monday 25 January 2010

Restrict Drop-Down (Combo Box) Display Number of Items

If you are using a combo-box anywhere and you are populating it with say 30 or 40 items you might - due to size and design constraints - want to restrict the amount of initial items in the drop down box. First of all your combo-box would usually be set up with it's data when the form it is on loads.

You would use the form load event. If this is not showing in your code you can simply select it using the drop down lists at the top of your code window.

Pick (Form1 Events) in the left hand drop-down box (Form1 or whatever your form is called)
Pick Load from the right-hand drop-down box
The event handler code will then appear in your code listing like this:

See here for explanation of how to create form load event

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
     
End Sub

In this handler you can put:

ComboBox1.MaxDropDownItems = 10

And it will look like this in the event handler:

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        ComboBox1.MaxDropDownItems = 10
End Sub

Meaning when the form loads the maximum amount of items the drop down will show out of your list of 30 or 40 will be 10.

Quite simple.

Tuesday 5 January 2010

Create and Call Another Form


From one form you can call another form quite easily. In this demo you will learn how to simply call another form using a button on the main form.

So if you are not using any of the projects from the last example you can create a new form/project with a button on it. There are details to do this here:

To Create a new project

To Add a Form

So once you have done this, or you have opened an existing project you can play about with, do the following:

1) Pull a new button on to the form as shown:



Note: If you have the label control on the form from previous tutorials then remember to check that the button and lable do not line up. We are not going to be activating the label in this exercise but this is good practice to make sure controls don't clash.

2) Give it a text property like 'New Form' without the quotes of course

3) Give the name property a name like btn2

4) Add a new form to the project as below, Right click Project > pick Add > Windows Form:





5) After that you will get an 'Add new item' dialog box with the windows form icon greyed out.

6) All you need to do is keep the name as form2, or whatever is your default, and click add.

7) Once you have the new form, go to form1 designer view and double-click the new button

8) In this click event that you now see, put in the following code:

 Form2.Show() 

As you type form2. you will be given a list of options to pick from after the dot, if you type s then h after the dot you will see the word 'Show' in the list being matched to what you typed. To select this you can either doubleclick on it or press the tab key. This is shown below:




9) Now all you need to do is save and run the form, then click the new form button and you will see your new form. Simple enough.



Sunday 3 January 2010

How to Use the Messagebox and Its Display Options

If you want to display an information or error message you can use either of two options in VB.NET:

1) MsgBox("My Message")

Or

2) Messagebox.Show("My Message", "Caption Information", Button Options, Icon Option, Default Button, Messagebox Options)

Generally you will only need a few of the options in the messagebox.Show(Options). All depending on what you want to do. I have only ever used the first three options but here is my explanation of the uses:

  • My Message = This is simply the message you want to display. The data type is string.
  • Caption Information = The information you want to display in the blue top bar of the message box. The data type is string.
  • Button Options = To get the button options put a comma after the caption and press space bar, a list of options will appear. These give you options for the types of buttons you want such "OK" only or "OK" and "Cancel" etc.
  • Icon Options = As before type a comma then space after the button options to give you the list of icons. you will have options such as information icon, error icon, exclamation, none, stop etc.
  • Default Button = This will allow you to select a default button if you have two or more buttons. 
  • Messagebox Options = This covers various options you will not be too concerned about if you are a beginner. I have not come across a time when I have used these options so feel it would be best not to go into this just now.

The first message box option (1) is carried over from VB6 and can be used in VB.NET as well. As far as I am aware it doesn't have the options available that messagebox.show has.

Lets show a messagebox on my experimental form. We will use a button to bring up the messagebox so you can simply use a new project or just a form as i am using for different exercises.

1) So if you open your  project (Or a new project) and place a button really anywhere on the form.

2) Click once on the button

3) Go to the properties of the button

4) Set the Text property to "Show Message box", without the quotes of course.

5) Expand the button design width so you can read the text on it

6) Double click on the button and you will get a button click event showing in the code as below



7) Put in this code:
    Messagebox.Show("My New Message")

8) Save the project

9) Run the project and click the new button "Show Message Box"

10) You should see the messagebox as below:



 As you can see there isn't much too it. Lets now add some more stuff to it to make it more interesting:

11) In you code add this:

MessageBox.Show("My New Message", "Show Message Box", MessageBoxButtons.OKCancel, MessageBoxIcon.Information)

Can you see what the new options are doing now?

12) Say you wanted to have a large message with breaks in the text you would use the following VB operator:

vbCrLf - Put this wherever you want a breakline in a message or string of text. You have to open and then close the quotes to put it in like this:

"I have a really long message " & vbCrLf &
"that I want to break into smaller " & vbClRf &
"lines so I use this technique"

The '&' is used to concatenate the strings together. The physical line breaks are only shown for illustration purposes. You could put all this code on one line. So here is how the message box looks now:




Remember to experiement with different options so you know what they do and how to use them.

Using 'With/End With' Statements

Instead of referencing the full name of a control for example we can use the With/End With statement. This allows us to reduce what we have to type if we anticipate that we will make many references to the control and it's routines.

The learning objective is to learn how and why the With/End With statement is used.

You might be referencing a textfield  in part of a statement as follows:

If Is Numeric(txtField.Text) Then
  txtField.Focus
  txtField.SelectionStart = 0
  txtField.SelectionLength = txtField.Text.Length
  Messagebox.Show("Value in text field must not be numeric.")
End If

But instead you could say:

With TxtField
If Is Numeric(.Text) Then
  .Focus
  .SelectionStart = 0
  .SelectionLength = .Text.Length
  Messagebox.Show("Value in text field must not be numeric.")
End If
End With

Notice how we do not need to reference the txtField now as we have said 'With TxtField'?

Can you see the dot (.) then the name such as Text, without the control's references i.e. TxtField? Because we have used the With statement we do not need to keep referring to the TxtField control.

This allows us to cut down significantly on the amount of typing we have to do when creating statements that refere to controls or other objects.

Saturday 2 January 2010

Setting Focus and Highlighting Text

In the last post I talked about setting focus back to a field when a validation check had failed. Usually when the focus is reset to a field that the user tried to get out of the text is highlighted, usually to indicate something is wrong with it.

Remember the validation event is oly triggered when focus is lost in a field i.e. when the user tries to move on to the next field or exit. If the validation fails the focus has to be returned to the field with the incorrect data in it.

If you want to highlight the text in the field you can use this after you set focus:

txtField.SelectionStart = 0

This piece of code puts the cursor at the start of the field.

txtField.SelectionLength = txtField.Text.Length


This piece of code sets the length of selection as the length of the text in the field, so it only selects that text and no more.

Validating

Validation is just a check for a certain piece of information and it usually done when focus is lost from a field. It is a critical part of any design as the cornerstone of most designs consists of information being placed into a database through these forms, and the data has to be in the correct format before it goes in. Generally there are validation checks being carried out in the Database but it can be helpful to catch any problems before this point within the application design.

For instance you may check that an email address has the '@' in it and say a certain prefix of yahoo, hotmail, google, netmail or any other web based email providers.

So for instance if you wanted to check if an email had the '@' symbol in it then in a validation event for the email field you would say:

If InStr(txtEmail.Text, "@") = 0 Then

MsgBox("The email must include the '@' symbol. " )

End if

The InStr operator checks 'In the String' for the value and the parameters you put in brackets are the (txtemail.text) field, and then what you want to find in the string i.e. the '@' symbol.

If the '@' value wasn't present then you would want to return the focus to the field until the value does include a '@' symbol. Within the code you would set the focus to the field if the check failed. This would return the user to that field until the check passed. If you did not do this then the user could move on and leave an unvalid value in the field. So the code would look like this:


If InStr(txtEmail.Text, "@") = 0 Then

MsgBox("The email must include the '@' symbol. " )
txtEmail.Focus()

End if

InStr returns a numeric value so if the value is 0 then this means the '@' symbol wasn't found.

You can do any checks at validation, this example is only one type of check.

Window State

When you run an application you may have a start up form and other forms that are called from this form. When you open any form you can have it set to open at maximum size, minimum size or normal, normal is the button you see in Windows at the top right of the screen, between the 'x' and underscore '_' .

If you want to set your form to be a certain size when you run the application, you set the property WindowState in the properties to the size you want : Minimised, Normal, or Maximised.

You can also set this at runtime wherever you choose. The code would look like this:

Me.WindowState = FormWindowState.Maximized

or if you were calling this routine from somewhere other than the form itself

form.WindowState = FormWindowState.Maximized

The form being the name of the form you are trying to change the size of.


Tab Order

What is tab order? Well if you go on to a web site or form, anything with controls (Buttons, Labels, Textboxes, combo boxes etc), and hit the tab key a few times you will see the focus moving through the different controls. For instance if you are logging in to a website you put in your user name then hit tab, this takes you to the next field for the password. In this case the tab order of the password field would come directly after the user name field.

Tab order is generally in number format and it is quite important to consider this when building a form with lots of controls. This tab order is part of the safety net that the user does not even realise is there. You may want a user to go through a form in a certain way so they do not miss information or processes that are needed to be carried out such as username then password in that order.

It's quite simple really, all you need to do to set tab order is click on each control in turn and set the tab order to reflect the tab movement that you want. The property is listed as tabindex and most controls will have a tab order. Anything that the user has to interact with will have a tab order property.

If there are controls that you do not want to be included in the tab order than just make the value much higher than the set of controls you have in the tab order. for instance you may want to exclude a critical button from a tab order, this is because a user can inadvertantly set focus and hit the return button, which will then activate a process you only wanted to be activated with the mouse.

The tab index will be set in the sequence of the order of the control that you put on the form, you may want to change this as you do your development work however.

Tab order can depend on many things, you may want to eliminate tabbing on buttons and only allow mouse clicks on them. this may be the case in a bank form where you transfer money by clicking a certain button. You wouldn't want the user to accidentally hit return after creating focus on that button with the tabbing key. Using the mouse makes the user think about what they are doing more than tabbing and hitting return to activate a button etc.

Generally speaking many people do not use tabbing and use the mouse to click in fields and on buttons, however commerical users and people who work with computers daily will generally be more accustomed to tabbing and it has to be built into any computer programme to handle this type of usage.