Showing posts with label Windows Forms. Show all posts
Showing posts with label Windows Forms. Show all posts

Monday, April 29, 2013

Visual C# Lesson 3: Using ListBoxes, arrays, and the string.Split( ) method

Introduction


In this tutorial, I'll go over another user interface ListBox control, which allows us to display items in a scrollable or drop-down style list.  We will also see how to split a string into separate strings that are stored in a string array, using the Split( ) method.

The ListBox and TextBox Controls

For this project, you should do the following:
  1. Create a new Windows Forms Application named Lesson3
  2. Resize the form so it is a little bit wider
  3. Place the following controls onto the form:
  • ListBox
  • TextBox
  • Button
ListBox
For this control, do the following:
  • Change the (Name) property to lstNameBox
  • Resize the height of listbox to make it a little bit taller than the default
TextBox
For the textbox, do the following:
  • Change the (Name) property to txtInput
  • Resize the width of the textbox so it is about as long as the form

Button
  • Change the (Name) property to btnPerformAction
  • Change the Text property to Perform Action
  • Make the button longer so it can accomodate the text

Programming the Event Handler

Again, we're going to make use of an event handler, which will respond to the button's Click event.  In the Design View, double click the btnPerformAction button to generate the event handler, and show you the Code View.

I'll show you the code, and then we'll discuss it.  Try to see if you can understand what's going on.  Pay close attention to the array declaration and the use of the for loop.


       private void btnPerformAction_Click(object sender, EventArgs e)
        {
            string[] nameArray;

            nameArray = txtInput.Text.Split();

            for (int i = 0; i < nameArray.Length; i++)
            {
                lstNameBox.Items.Add(nameArray[i]);
            }//end for
        }

First, look at the array declaration.  Notice that it is slightly different than an array declaration in a language like C++.  You put the brackets, [ ], after the data type instead of after the identifier.

Below that, we use the string class's Split( ) method on the txtInput's Text property, which, by default splits the large text string into individual strings, delimited by spaces.

The for loop is very interesting.  In C#, arrays are classes and have properties.  The Length property is extremely useful, because it tells us how many items are in the array.

Inside the for loop, we access the lstNameBox's Items property, which is a collection, an array-like structure that can hold items in its own right.  Item-by-item, we call the Add(  ) method of the Items property, to add these individual items to the list box.

Running the Program - Round 1

To use this program, simply type a list of names, separated by spaces, in the textbox.  Then, click the Perform Action button.  Watch the magic.

 

It is pretty straightforward, but there is what could be considered a simple bug.  Click the button more than once and observe what happens.  It adds the list multiple times.

Fixing the Multiple Listing Bug and Running the Program - Round 2


So, how do we remedy this so that only what is in the textbox is split and displayed once?  We use the Clear( ) method of the listbox's Items collection each time before we enter the for loop.  Let's see our new code.


    private void btnPerformAction_Click(object sender, EventArgs e)
        {
            string[] nameArray;

            nameArray = txtInput.Text.Split();

            lstNameBox.Items.Clear();
            for (int i = 0; i < nameArray.Length; i++)
            {
                lstNameBox.Items.Add(nameArray[i]);
            }//end for
        }

Run the program again and try clicking the button multiple times.

This solves the problem.  One simple line of code.  We tell the listbox's Items property to empty itself before we go into the loop to add the items from the text box.

Summary

In this tutorial, we got our feet wet with yet another Windows Forms control.  This time, the ListBox.  We learned how to add elements to the listbox's Items property, which is a member of the ListBox class, and is an object collection.  Clearing the list was a piece of cake, with only one line of code being necessary.

We also learned about arrays - how to declare the array, and then assign it to another array.  In this case, the Split( ) method of the string class returned an array for us.

Visual C# Lesson 2: Labels and TextBoxes

Introduction

In this tutorial, we will explore adding and interacting with labels and textboxes in Visual Studio 2012. 

I assume you know how to create a Windows Forms Application, as described in Visual C# Lesson 1.


Adding a Button, a Label and a TextBox

A label is a user interface control that is typically used for displaying information.  This information could be static information - like a basic "signpost" telling the user "hey, here is where you enter your name:", or it can be used to output information to the user in a more complex fashion.

A textbox is a control that is typically used to obtain user input.  The user types something in it, then sometime later, your program makes use of this input.

Before we proceed, let's add the two user interface controls. 

  1. Create a new Windows Forms Application in C# and name it Lesson2
  2. Drag a Label control from the Toolbox onto the form
  3. Drag a TextBox control onto the form
  4. Move the textbox so it is near the top of the form, and make it a little wider using the sizing handles
  5. Move the label so it's a little bit under the textbox
  6. Add a Button onto the form and put it near the bottom of the label and textbox
It should look something like the following when you're done with the above steps:


 

Now we need to modify the properties in the Properties window.  For each of the controls, make the following modifications:

The label1 label
  • Change the (Name) property to lblOutput
  • Remove the text in the Text property entirely
Don't be afraid that you can't "grab" the label easily on the form in Design View anymore.  It's actually very easy to select it again.  You just go to the drop-down above the Properties window and select the control you want.


The textBox1 textbox
  • Change the (Name) property to txtInput
Since textboxes do not contain text by default, you don't have to modify the Text property

The button1 button
  • Change the (Name) property to btnExecute
  • Change the Text property to Click Me!

Generating the Event Handler

Just like we did in Lesson 1, double click the btnExecute button to generate the event handler.  You are now in the Code view.  Inside the event handler, you will add statements to simply set the lblOutput label's Text property equal to the Text property of txtInput.

Let's look at the code I've added:


       private void btnExecute_Click(object sender, EventArgs e)
        {
            lblOutput.Text = txtInput.Text;
        }

This code is fairly straightforward.  I'm saying, "When the user clicks the button btnExecute, set the lblOutput's Text property equal to the Text property of the txtInput text box."

So, all three of our controls are playing a part in this.  The button is used as the "signaller" to the program to say "do this...".  The label lblOutput has its Text property changed to whatever text string is in the txtInput text box's Text property.

Observing the Output


Build and run the application and then put your name in the text box, and click the button.  The label will echo the text in the text box.  You can keep modifying the text in the text box and clicking the button and it will update the label's text.

 
 

Summary

 

This very simply application gives us insight into the inner-workings of a Windows Forms application.  Specifically, we looked at how we can use labels, textboxes, and buttons to interact with the user.  If you're coming from a programming language where you wrote Console applications, then you're used to writing code and having it execute in a realitvely sequential manner (with slight variations due to our selection and repetition control structures like if-statements and while-loops.)

This paradigm of programming we're using is called event-driven programming.  Event-driven programs respond to, well, events!  An event can be a number of different things - clicking a button, typing in a text box, the selected item in a drop-down menu (ListBox).  The sky is the limit.  We will explore more as I write more tutorials.



Visual C# Lesson 1: Introduction to Windows Forms Applications in Visual Studio 2012

Introduction

In this tutorial, I will be showing you how to create a basic Windows Forms application using C# in Visual Studio 2012.  If you have an earlier version of Visual Studio, or a different edition, don't worry.  Many of the steps are very similar and some are even identical.

Creating a New Windows Forms Application


Before we get started, a couple basic concepts if you're new to Visual Studio:
  • A project is a collection of source code files and resources (configuration files, images, etc.)
  • A solution is a collection of one or more projects.
Thus, a project lives inside a solution, and source code and resources live inside a project.  Simple enough for now?  Ok let's get going.


To create a new Windows Forms application:

  1. Open up Visual Studio
  2. Click on File
  3. Hover over New
  4. Click Project
 

When the New Project window is displayed, you should make sure you are under C# as the language.  Then, you should do the following:

  1. Verify you have Windows Forms Application selected
  2. Change the name of the project to something meaningful
  3. [optional]  Select the Browse button and move the location of the project to some location you want to keep your solution.
  4. Click the OK button


This will generate the configuration and setup files necessary for your solution.  You should now see the basic Design View for a Windows Forms application as the largest area in the visible interface.  Before we move on, I want you to add one more thing.  You need the toolbox, so we can actually add items to the form.  If you already see it, then ignore these steps:

  1. Go to View
  2. Click Toolbox
 
 
Usually, I like to dock my toolbox as a tab along with Solution Explorer.  Visual Studio has kind of a strange docking mechanism that you have to get used to.  Click and drag the Toolbox that appears over the Solution Explorer and then hover over the center docking control and release the mouse.  It should look something like this (note I've moved my tabs around a bit.)
 




  Now, there are four major "parts" I want you to be aware of are:
  • The Design View
  • The Solution Explorer
  • The Toolbox
  • The Properties Window
The Design View contains the area where you can place and select controls, such as buttons, text boxes, labels, and other user interface objects.

The Solution Explorer contains the projects in your solution.  You'll start out with one project, and it is often the case that you will only have one projects, even for many medium sized software applications you'll work on.

The Toolbox, in the docking format I selected, is available by clicking on the botton tab to switch back and forth between our Solution Explorer and Toolbox.  It contains the controls that we can add to our form.

The Properties Window contains various properties of a control, such as the programmatic name (the variable's identifier), the display text, the color, styles, and many others.  This window is also where you can view various events associated with the various user controls.

A Simple Example with a Button

Let's create a very simple application that simply allows the user to click a button, and says "Hello!" to the user.

  1. From the Toolbox, drag a Button control (which is under All Windows Forms) onto the form in Design View.
  2. In the Properties Window, change the (Name) property to btnPressMe, which will be the name of the button used in the actual code we are about to write.  It is a convention, but not required to start a button control identifier's name with btn.
  3. Change the Text property to Click Me
Your form should now look something like the following:



Now we have our basic button ready.

Build and Run the application as follows:

  1. Go to Build
  2. Click Build Solution
  3. Go to Debug
  4. Click Start without Debugging
Now click the button.  But wait.  It doesn't do anything.  Why is this?

This is because you haven't added an event handler to it.  Close the executing Form1 application and go back into Visual Studio.

Adding an Event Handler to the Button

In Design View in Visual Studio, double click the button on the form.  It will generate an event handler for the button and link it automatically.  There are many different events to choose from.  For buttons, the default event is Click.  This code that you will write in this method is what will execute when a user of your application clicks the button.

So what can we do?  Since we don't know too much just yet, let's just have a Message Box pop up and tell the user "Hello!"

Make your button's event handler match the code inside the body of mine:


      private void btnPressMe_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Hello!");
        }

Now build and run the application in the same manner you did before (Build --> Build Solution, then Debug --> Start without Debugging.)

See?  If you click on the button, you now get a message!