Skip to content

Recent Articles

2
Aug

Lesson 54 – File access in Windows Forms (SaveFileDialog & OpenFileDialog)

In this lesson we’ll expand on the reading/writing of files we did earlier by introducing controls that allow the user to pick where a file should be saved to/opened from.

  • Create a Windows Forms Application
  • Add two Button controls to your form (one for saving and one for loading) and name them appropriately

File Access

Even though we’re now working in a graphic environment, the fundamental tools we used for reading/writing files back in Lesson 21 – Writing text to file and adding a linebreak to a string and Lesson 22 – Reading text from a file still apply.

Now, we’re simply going to add some nice, built-in, graphical ways for the user to tell us where they would like to read/write their file to/from.

Saving

We are provided with class named SaveFileDialog which grants us the ability to ask the user where they would like to save a file.

This class contains options for things like only showing certain file extentions, what directory should the dialog show by default, etc.  We won’t go into these details here, but they would be an excellent thing for you to do some of your own research into when you need to save a file.

Once we know the result was that the user clicked on the OK button (which the DialogResult tells us), we can open save the file just like we did back in Lesson 21 – Writing text to file and adding a linebreak to a string

This time, however, the user is providing the file location instead of us having to hard-code the value.

Open sesame

The process for having the user select a file to open is almost identical to that of having them select a location to save.  For this, we use a class named OpenFileDialog.

Again, once you have a DialogResult.OK, you can use the dialog.FileName property to read the file as you did in Lesson 22 – Reading text from a file

2
Aug

Lesson 53 – Lists for the user (ListBox)

In this lesson we’ll discuss the most basic control for displaying lists of information to the user, the ListBox, and the basic ways we interact with it.

What is a ListBox

If you use a computer (which you clearly do), you have undoubtedly seen a ListBox before.  They are basically simple lists of info which often have a scrollbar to scroll through the contents if they take up more room than is available.

Filling a ListBox… from code

A ListBox without items doesn’t do us much good.  Fortunately, they are easy to fill using the Items property’s Add method.

So, when we run the program, we get:

Which one did the user pick?

So, now we have a list of people for the user to pick from, but how do we know which one they picked?  The answer lies in the SelectedItem property.

Note: if the user hasn’t selected anything in the list yet, SelectedItem will be null

Note: I added a Vote button

Up to the minute news

The above example will let you ask the ListBox what it has selected when you feel like it, but what if you want to know when the SelectedItem changed?  We have an event for that, just like our Button control has a Click event (Lesson 46 – Informing users (message box) and responding to their actions (events) ).  This event is called SelectedValueChanged.

2
Aug

Lesson 52 – MessageBox, more than just a pop-up

In this lesson we’ll discuss how we can use our MessageBox.Show method to not only display information to the user, but also get answers from them.

  • Create a Windows Forms Application

Pop-up

Previously, we’ve simply used the MessageBox.Show method in the same way we used Console.WriteLine:  to simply output some information to the user.

Input

When we type MessageBox.Show, we see there are many different overloads (like we discussed in Lesson 50 – Methods by the same name (method overloading) ). 

For our purposes in this lesson, we’re going to work with number 5, which takes two strings and a MessageBoxButtons (which is an enum like we talked about in Lesson 51 – Better names for hard-coded values (enums) )

So now, instead of just passing the message we want displayed, we are also passing text to put in the caption (text in the pop-up’s header area), and an enum that says what kinds of buttons we want displayed.

NoteÂ
MessageBox.Show actually returns a value, which is another enum of type DialogResult.  The value returned indicates which button the user pressed, which we store in a local variable named result.

That’s what he/she said

Using our overload version of MessageBox.Show, we can now ask the user a question: 

  • We control the message (which we can word as a question)
  • We control the buttons the user sees (MessageBoxButtons.YesNo, for example)
  • We get their response (which button they clicked) returned to us.

Now that we know what they want to do, we can have different code run depending on their answer.

 

2
Aug

Lesson 51 – Better names for hard-coded values (enums)

In this lesson we’ll discuss hard-coded values, some of the bad ways to deal with them, and one of the better solutions to those problems.

  • Create a Windows Forms Application

Hard-coded values

It is often the case that we have a pre-defined set of acceptable values for a certain piece of code.

Say we have a Character class and we want a Character to be able to perform a certain set of pre-defined actions (Move, Jump, Attack).  Also say we want to have a single method, PerformAction, where we can just tell it which action to do and have it figure out what needs to be done.

Number values

One of the very basic ways we could handle this would be to assign each action a number (in our head), and just take that number as a parameter for our PerformAction method.

The Problem
Outside of our little comments, there’s no clear definition saying that 1 means Move, 2 means Jump and 3 means Attack.

Also, what happens if we pass 4… 5… 382371?

String values

Okay, so numbers aren’t very descriptive.  What about string values?  We could just pass “Move”, “Jump”, “Attack” and we’ll know exactly what it is we are passing!

The Problem
Our string actions are a bit more descriptive, yes, but there’s a problem.  What happens if I put in a typo (“movie”, “atack”, etc)?  If the value of action doesn’t exactly match the expected value, it’s not going to do what we want it to do.

Enums to the rescue

So, we know that numbers and strings aren’t great solutions.  Thankfully, we are provided with a solution that solves their issues: the enumeration (or, much more commonly, enum).

An enum is a type we create (much the same way we create a class), which allows us to build a pre-defined list of acceptable values that we can’t go and easily screw up.

Now that we have these three values defined, and nicely grouped together in this new type we created, we can re-write our PerformAction as such:

The Benefits
Using our enum instead, we enjoy a few benefits:

  • Self-describing (no comments like the int)
  • No chance for typos (unlike the string)
  • Intellisense help (Visual Studio knows what all of the acceptable values are, and gives you a list of them when you type CharacterActions.)
  • Much harder to to pass an unacceptable value (not impossible, but not something you need to worry about in almost all cases)
2
Aug

Lesson 50 – Methods by the same name (method overloading)

In this lesson we’ll discuss the concept of having multiple methods with the same name, and why this can be useful.

  • Create a Windows Forms Application

A method by any other name…

Up until this point, we’ve lived by the general rule that method names had to be unique within a class. 

However, we can actually make multiple methods with the same name so long as we follow certain rules.  We call having multiple methods of the same name method overloading.

So, what are the rules that allow us to do this?  Simply, the types of the parameters passed to the method must be different (and just having a different return type doesn’t count).

Here’s a few examples (with comments explaining each, whether they would work or not).

Why?

You may be wondering why we would ever do this?  The simple answer is that it allows us to group very similar pieces of functionality into a nice, concise package.

When we go to call our Add method, Visual Studio recognizes that there is more than one overload and gives us a list to choose between, which we can cycle through using the arrow keys.

(Note the 1 of 3)

Practical application

The most common scenario where we use method overloading is when writing class constructors. 

This enables us to provide options as to whether we want to create an object using default values for its properties, or if we want to provide it values when the object is created (like we did in Lesson 39 – Passing parameters when creating new objects (constructors)).

16
Mar

Micro-assignment 8

In this assignment you’ll build a simple application using two forms which does a bit of validation and uses a few of the more common controls.

  • Create a Windows Forms Application
  • Create two forms: LoginForm and AdminForm
  • Any control you access via your code should have an appropriate (and non-default) name given to it.

LoginForm

  • Create textboxes with appropriate labels for the user to enter username and password
  • Create a login button
  • Handle the login button’s Click event.
    -  If the username/password isn’t james/bond, inform the user that the login failed
    -  If the username/password is correct:
        +  Create a new instance of AdminForm and display it
        +  Hide the login form
        +  Handle the FormClosed event of your AdminForm object, and call “this.Close();” inside that handler (this will ensure that your program exits when the user closes the admin form)
        +  Show your AdminForm object

AdminForm

  • Create a checkbox for “nap first”, a textbox for “target location” (with appropriate label), a button for “fire missiles”, and a label to display your results
  • Handle the “fire missiles” Click event
    -  If the location textbox is empty, inform the user
    -  If the location textbox has been filled, set the display label’s text value appropriately, based on the checkbox and the text entered in the location textbox.

Extra Credit

  • Make the password box display *’s instead of the actual text being entered.

Sample Application

Cheat Sheet

16
Mar

Lesson 49 – Hunting down problems (debugger)

In this lesson we’ll discuss the very basics of hunting down problems using Visual Studio’s powerful debugging tools.

  • Create a Windows Forms Application

Pest control

There will be times, lots of times, where your program won’t do exactly what it’s intended to do.  We call these issues bugs. 

While it is highly unlikely that you will ever get rid of every single possible bug in any non-trivial application, debugging is a major part of software development and is something you’ll want learn early, use it often, and become proficient with the tools available as quickly as possible.

Because hunting down bugs is such a major part of developing software, Visual Studio provides us some very powerful and robust tools for helping us find out bugs.

For now, we’ll just cover the basics.

Walking through

The most basic concept in using a debugger is the breakpoint, which tells Visual Studio “when you get to running this line, I want you to pause and let me take a look under the hood”

We place breakpoints by clicking on the little light-gray bar to the left of our code by the line at which we want to “pause”, which causes a red circle to appear and the line’s background to be highlighted in red.

Now, when we run our program with debugging (i.e. F5 or Debug->Start Debugging), Visual Studio will pause the program at that line and let us look around.

The yellow arrow/highlight tells us that Visual Studio has paused the program, and is waiting for us to do something at the highlighted line.

Moving on

Once we’re in the debugger with the program paused, we can control, step-by-step, the execution of the code and check the values of variables, etc.

There are four basic controls you’ll use here.  Continue, Stop Debugging, Step Into, and Step Over.

Note:  This control bar might not show up in the same place for you as it does in these position.  If you don’t see it at all, right-click anywhere in the toolbar and make sure Debug is checked

Breaking it down
Continue – Will cause the program to continue running until it hits another breakpoint, or doesn’t find anything else to run.

Stop Debugging – Will stop running the program altogether (usually useful when you’ve figured out something you need to change, and just want to get back to the code to change it)

Step Into – Will move the debugger to the next line.  If the current line calls a method, it will move into the first line of that method.

Step Over – Will move the debugger to the next line.  If the current line calls a method, it will execute that method and continue onto the next line in the current method.

Additional note:  You’ll want to become familiar with the keyboard shortcuts for these commands (especially Step Into (F11) and Step Over (F10)).  Will make your life a lot easier and your debugging much quicker.

What’s the value

Now that we can walk our way through a program, we’ll want to actually be able to see what’s going on in our program.  There are several ways to do this, but we’ll just cover two very basic ones for now:

  • Mouse over
  • Autos

Mouse over
Pretty much just what the name says.  If you’re debugging an application, you can mouse over a variable and see it’s current value.

Autos
Visual Studio provides a window that will automatically provide variable information that it thinks might be useful to you, based on where you are in the process of executing your program. 

If you don’t see this window, you can open it while you’re debugging by going to Debug->Windows->Autos

The Autos window looks something like this, and again, it’s contents will change based on where you’re at in your application.

Closing comments

The debugger in Visual Studio is exceptionally powerful (and probably the best in the industry), and you definitely should learn to take advantage of it.

Spend some time messing around with breakpoints, stepping through an application, etc.

Here’s the simple code I made for this lesson, feel free to slap it into a new Windows Forms Application, or write your own methods, etc, and try things out.

Sample

7
Mar

Lesson 48 – Providing generic functionality for multiple classes (inheritance)

In this lesson we’ll cover the basics of a new OOP concept called inheritance, which allows us to write code once and have multiple classes use that code.

  • Create a Windows Forms Application
  • Create class files as specified

Derivative works

It is often useful for us to be able to create functionality that is used in multiple classes.  To accomplish this, we have a concept called inheritance.  To put it simply, when a class inherits from another class, it gets that class’s variables, properties and methods as if it had defined them itself.

We call the class containing the generic functionality a base class and the class inheriting it a derived class.

How they’re created

The format for making a class inherit from another class is very simple, and something we’ve seen (albeit, haven’t mentioned) in our Form classes.

The part we’re interested in right now is the : Form.  What this is saying is that our class, Form1, is inheriting from the class Form, which is provided for us. 

This allows us to use methods, etc that are defined in Form (i.e. Show and Close from Lesson 47 – Multiple forms), even though we didn’t create them ourselves.

Making an example

To illustrate this concept, we’re going to create a few of classes and add to them some functionality that is generic and some that is specific.

Breaking it down
In the example, we see that our Player and Monster classes both inherit from our Character class (i.e. Player/Monster : Character)

Because they inherit from Character, both classes have Name, Kill and hitPoints defined in Character.  Since MakeHeroic and MakeEvil are not defined in the base class, but in the derived classes, they remain only available in their respective class.

What is a protected?!

We snuck in a new keyword in this example; protected.  Much like the public and private we’ve seen before, protected is what we call an access modifier.

We remember that public means “anyone can see/use this” and private means “only I can see/use this”.  In this same line of thinking, protected means “only myself and classes that derive from me can see/use this”.

To illustrate this, you can see that because hitPoints in Character is protected, we can access it inside both Player and Monster, but not from within Form1.  On the same note, because name in Character is still private, neither Player nor Monster can see it (though, they can of course see Name, as it is a public property).

7
Mar

Lesson 47 – Multiple forms

In this lesson we’ll discuss how you can have more than one form in your application, and how you can interact between forms.

  • Create a Windows Application
  • Add your code as specified

Adding another form

Since a form is just a class (albeit, a complex and magical class), we can add more forms to our project in just the same way we add additional class files.

We see that our new form (i.e. Form2) is now in our Solution Explorer, and we can work with it just the same as with our original form.

Show me the form

Additional forms are often used to provide functionality that can be fairly complex, but isn’t something we want in front of the user all the time (i.e. when you added your form, Visual Studio brought up the Add New Item window).

As such, we’ll generally trigger the showing of the form in a user event, like a button click.

We see that in our click event handler, we are creating a new Form2 object (remembering that Form2 is just another class).  Our object (i.e. secondForm) has a method named Show, which we call to display the form.

Closing a form

Generally, when the user is done doing what they need to do with our form (say, they clicked a Save button or something), we’ll want to to close the form for them.  In this case, our form provides a Close method, which we can simply call when we’re done doing what we need to do.

3
Mar

Lesson 46 – Informing users (message box) and responding to their actions (events)

In this lesson we’ll cover a simple way of providing information to the user, as well as writing code that is executed in response to having them interact with a control.

  • Create a Windows Forms Application
  • Add a button to your form, and give it an appropriate name

Talking back

Much the same way we use Console.WriteLine to display text to a user in a Console Application, we have a simple tool for providing text information to our user in Windows Forms.  The tool in question is a static method of a class called MessageBox, named Show

Note: we’re going to use this a fair amount in our examples because it’s very simple, but out in the wild you’ll want to use this method of giving the user information judiciously because of the way they “pop up” in front of the user.  Anyone that’s used a computer in the last decade knows how annoying the over-use of pop-ups can be.

Click it

When we add a button to a form, it seems fairly obvious that we’re going to want to do something when that button is clicked.  How do we know when the button is clicked?  Well, it tells us.

The way the button tells us that the user clicked it is by way of what we call an event.  To put it simply, an event is a way for an object to broadcast, to anyone that cares to listen, “hey, something happened over here”

So, in the case of our button, we have an event named Click that will tell us when the button was clicked.

When we write code that we want executed in response to an event happening, we call that handling an event.  The syntax for handling an event is a little different, but fortunately Visual Studio makes it easy for us.

Breaking it down
So, we typed DoItButton. and found an entry named Click with a little lightning bolt next to it.  The lightning bolt icon indicates that Click is an event.

When then typed +=, which seems a bit odd because up until this point we’ve only seen this operator when we wanted to add a value to the current value (i.e.  someInt += 5;).  Simply put, the reason behind this is that the event handling we’re creating isn’t exclusive; we’re not necessarily the only one listening.  Because of this fact, we can think of this as saying “hey, add me to the list of people that want to know when this happens”

The next two steps, Visual Studio made our life easy; we simply had to press the Tab key twice.  The first time generates the code we need to handle the event, and the second time actually creates the method that is going to get called when the event happens.

Our response

So, now we have a method that will get called when our button gets clicked (i.e. DoItButton_Click), so we simply need to put the code we want executed inside of this new method.