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.