Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
February 2007
Having C# without the “.NET Framework” is about as useful as a pen without ink. You can write all you wish, but you’re not going to achieve anything useful.
What is the .NET framework? It is a programming platform developed by Microsoft. C# was specifically written as a language that will use the .NET Framework. The framework is made up of two different things:
A huge library of code that we can call from our C# programs. This saves us writing everything ourselves.
A “runtime” module, which runs our programs for us when we’re ready (this happens invisibly - you don't need to worry about it)
When you write a C# program (or a program in any of the other .NET languages), you typically call some code that lives in the library, as well as writing some of your own code.
There are so many classes in the .NET framework, and some of them are pretty complicated, so we certainly won't try to cover the whole thing here. Instead, this section's chapters go through some of the .NET framework classes that we think you'll find most useful. As you grow in experience, you'll find that there are certain classes that you use often and you'll get to know those ones well - like taking a favorite book out of the library - eventually you know just where to find it.
It's very important to realize that part III is not just for reading - these chapters include a lot of sample programs and you're supposed to try them all out for yourself and then try changing them to do new things.
In the following chapters, whenever you see a block with the words "code for program ...” you can run that code using Visual C# Express. Although most of these programs are short, they are all real working programs. Here are the steps you will normally follow:
Open Visual C# Express. Select File -> Open Project and then browse to wherever you saved the example programs. Open any file with a ".csproj" extension.
(or you can use Windows Explorer to find the sample you want and simply double-click the .csproj file.)
Press F5 to run the program (or click the green arrow)
It's fine telling you "you can change the examples", but how do you know what to change them to? The examples show a few .NET Framework classes and methods being used - how do you know what other ones are available? There are a few ways to find out:
Look through the .NET Framework SDK Class Library included in Visual C# Express's help.
While programming in Visual C# Express, to see the available classes, methods, fields, etc for a class, press the "." key directly after typing a namespace or class name. E.g. Type "Console." and you'll see a list of methods and other members available in the Console class.
In the case of a method, if you type an open parenthesis at the end of the method name, you can also see the parameter types that the method expects. Often a method is written in a special way to allow different sets of parameters - then you can scroll through them by pressing the down and up arrow keys. The following example shows what happens when you type "Console.WriteLine(". Visual C# Express shows that there are 19 different ways you can call WriteLine. In the picture below, we pressed the down arrow until we reached the 11th one.
The idea of a “Console” comes from the days when large mainframe computers were very popular. A company would have a giant computer hiding in some back room and the people outside would have a keyboard and a simple screen, called a console, which was hooked into the beast in the back room. These screens could not display true graphics – only text. The keyboard was the input device, sending information to the computer, and the console was the main output device, allowing to computer to send information back to the user.
The world moved on and these days most computers use displays that can show far more natural representations to people than lines of text – photographs for example.
There is often a need, however, to do things that don’t need to show anything fancy to the user. You may, for example, have a program which goes and fetches some data from an Internet server somewhere and puts it into a file on your pc. If all you need it to say is “busy fetching data” and then “done”, why waste a whole lot of time and memory on a fancy user interface? It is for this reason that the .NET library offers us a class for easily writing console applications.
Don’t scoff at console applications, as if “they aren’t cool”. In fact, you’ll find the really smart programmers get tired of wasting time with fancy interfaces and do most of their own work in console applications.
Of course, if you plan to write a program that someone else is going to use, you probably want to be a little kinder and give them something friendlier than a console interface.
Some Useful Methods
Console.ReadLine – reads a line of text from the keyboard (or some other input device)
Console.Read – reads a number from keyboard (or some other input device)
Console.WriteLine – writes text to the screen (or other output device), starting on a new line
Console.Write – writes some characters to the screen without starting a new line
The following program simply writes the word "Yo!" to the screen and then waits for the ENTER key to be pressed.
Code for program 1 |
|
The following program
Asks the user to type in a word on the keyboard
Asks the user how many times the word should be written out
Writes out, on a new line each time, the word that was entered, as many times as was requested
Code for program 2 |
|
If you want to write programs that look and feel like the ones you’re used to using in a Windows environment, you’ll most definitely want to use the classes in the System.Windows.Forms namespace. They allow you to work with buttons, list boxes, text boxes, menus, message boxes and a whole bunch of other “controls.” Controls are things you place on a form – they either show things like text (a Label control) and pictures (a Picture Box control) or allow you to carry out actions such as selecting a value or clicking a button to move to another form. You’ll probably use the classes beneath System.Windows.Forms in most of your C# programs.
Obviously the idea of a “form” comes from the widely used paper form in the “real” world. A form is something which allows the placing of various things (text, pictures, entry boxes, etc.) in a well-organized layout. Generally, a person will read some information on the form and fill in some information in particular regions.
The idea on the computer is similar – a form allows the placing of text, pictures, entry boxes, buttons, etc, in a fashion which allows these to be precisely organized on the screen - very different to a console application, which can only handle lines of text following each other.
Microsoft has provided, in the .NET Framework class library, a huge number of “controls” for use on forms. Once you know how to place a control on a form, you can build up a snazzy application very quickly, simply by using these existing controls.
The following are examples of classes with code for controls that you can place on your forms
Label
Button
ListBox
CheckBox
RadioButton
ListBox
Menu
TabControl
Toolbar
TreeView
DataGrid
PictureBox
RichTextBox
To play with the following examples in C# Express, you can select File -> Open Project and open the book's sample .csproj programs from wherever you chose to save them on your computer's disk.
If, however, you want to type them yourself from scratch, you need to be aware that when you create a new "Windows Application" project, C# Express puts down some .cs files for you (named Form1.cs and Program.cs), and inserts some C# code so that you're ready to go. It actually creates for you a basic but fully functional program. While you're working with the examples below, to keep things simple, you should probably
delete Form1.cs and
replace the code in Program.cs with the code from the example you're working with
This is not necessary if you rather open the examples using File -> Open Project.
Here’s an absolutely simple Windows forms application. All it does is to start a new form and write some text in the titlebar of the window.
Code for program 3 |
|
This example is simple too, but takes us to the next level – placing a button on the form
Code for program 4 |
|
Having a button on the form is okay, but in the example above, nothing happens when the user clicks the button. Boring.
We need to write a method that will do something when the button is clicked - let’s just make it change the Title Bar text in this case. We call such a method an event handler, since it will watch for an event (a click in this case) and will then decide how to handle it. We also need to hook the button click event up to the event handler.
Code for program 5 |
|
|
Right, the program does all the basic stuff. Now let’s add a few other types of controls to the form, lay them out nicely and work with them a little. We'll use 4 control types: Button, ListBox, MessageBox and PictureBox.
Notice that, apart from System.Windows.Forms, we'll also use the System.Drawing namespace here. This is necessary because we're using a PictureBox - and working with images requires the Drawing classes.
Code for program 6 |
|
Okay, now let’s get wild. To illustrate how to use some of the other controls, we’ll write one really large program including many useful controls. This will make the code scarily long, but it will be a useful program for you to refer back to when you need to use a particular control.
You don't have to read the entire program in detail, but when you're interested in using, for example, a CheckBox, come back to this program, find the parts that talk about CheckBox and study those parts.
Notice that in order to use the PictureBox and the DataGridView in interesting ways, we're also going to use the namespaces System.Drawing, System.Data and System.Xml;
Code for program 7 |
|
The classes grouped together in the “Drawing” namespace allow us to work with different types of pictures. On computers, we usually deal with two general types of pictures:
Bitmap or Raster graphics |
Vector graphics |
---|---|
![]() |
![]() |
Bitmap graphics are pictures made up of many dots. For example, photographs and icons can be represented well as bitmaps. |
Vector graphics are pictures made up of specific shapes like lines, circles, rectangles, etc. A house plan, for example, can be nicely represented using vector graphics. |
First, we'll show some examples of how to work with bitmap graphics. It is often useful to work with pictures such as photographs on the computer, and the .NET Framework class library includes quite a lot of useful code for doing so.
This program simply fetches a bitmap image (a JPEG file in this case) from the disk and displays it on a form.
To display an image on a form, it is helpful to use some control that is capable of displaying images. The PictureBox control is perfect for this purpose.
Code for program 8 |
|
This next program loads a photograph from disk and then also allows the user to flip it horizontally by clicking the "flip" button.
Code for program 9 |
|
Now let's move on to examples dealing with vector graphics - pictures that are made up of specific shapes.
In all of these examples, we'll create a button and an event handler method to catch the button's click event. Only once the button is clicked will we run the code that works with the graphics.
Here are some important concepts to understand. They're very logical - but if you didn't know these you might feel a little confused:
In the real world, to draw a line, circle, rectangle, etc, you first need to select a pen of the correct color and thickness.
Similarly, to draw a plain shape on the computer, you must first create a Pen object. For example, this code creates a Pen object that will draw in green with a thickness of 3 pixels :
Pen myGreenPen = new Pen( Color.Green, 3 );
To create a colored-in shape, you could use something like a paintbrush.
On the computer, colored-in shapes can only be created if you have created a Brush object with some chosen color. There are different types of brushes available; the following piece of code will create a blue SolidBrush object :
SolidBrush myBlueBrush = new SolidBrush( Color.Blue );
In this program, the DrawSomeShapes method creates a line, a rectange and an ellipse (a squashed circle).
Code for program 10 |
|
How about we have a bit of fun with the mouse now? Doing interesting graphical things is usually easier with a mouse than with a keyboard. In this next example, we work with both bitmap and vector graphics but also take the opportunity to use a few mouse events.
We do a few interesting new things below - particularly with bitmaps. Although we don’t want to write an essay about it, here’s a little bit of background to help you understand the concepts behind the code:
Computer programs make graphics appear on the screen by changing the color and brightness of tiny dots called pixels.
Each pixel is made up of the three primary colors: red, green and blue (often shortened to RGB in programming languages). You change the color/brightness of the pixel by varying the strengths of the R, G and B, typically between the values of 0 and 255. For example:
if red=255 and green=0 and blue=0, the pixel will appear bright red.
if red=255 and green=255 and blue=0, the pixel will appear yellow.
The mouse’s position can be detected by the computer and is specified in terms of X and Y co-ordinates (horizontal and vertical co-ordinates). The top left of the screen, for example, is specified by X=0 and Y=0.
Code for program 11 |
|
Most applications out there need to work with databases. Ask any big company's programmers and you'll hear them speak about how important databases are in the computing world. A programmer who can work with databases will be in a position to create a great many really useful applications.
You might have a database such as Microsoft Access on your computer. Alternatively, you could install Microsoft SQL Server Express Edition, which is a really nice way to learn about the SQL Server database, used in many of the largest companies around the globe. SQL Server Express is available as part of the Visual C# Express installation, so you may already have it installed.
The System.Data classes in the .NET Framework allow you to work with databases. A database is quite different to things like pictures and word processor documents, which are often called unstructured. A database is more structured. It most often contains many rows of the same type of data, grouped into blocks called tables. The table contains one or more columns and each column holds a particular piece of information for that row.
Rows are sometimes called records and columns are sometimes called fields. |
Here is a representation of a database table that holds information about planets. The columns in this case are PlanetName, DistanceFromSun and Inhabitants.
PLANET |
||
PlanetName |
DistanceFromSun |
Inhabitants |
Mercury |
57909 |
Mercurians |
Venus |
108200 |
Venusians |
Earth |
149600 |
Earthlings |
Mars |
227940 |
Martians |
Jupiter |
778400 |
Jupiterians |
Znock |
7208100 |
Znockers |
Saturn |
1423600 |
Saturnians |
Uranus |
2867000 |
Uranians |
Neptune |
4488400 |
Neptunians |
Pluto |
5909600 |
Plutonians |
You can see, for example, that the planet Venus is 108 200 thousand kilometers from the sun and that the creatures living there are called Venusians.
Here's another table, this time showing how many creatures were found living on the planets each year.
This is top secret information never revealed before. It was retrieved from an alien craft that crashed in a remote part of the Gobi desert. You should feel privileged to have a copy. Apparently, they too use SQL Server Express databases, which made it easier for us to bundle a copy with the code samples.
POPULATION |
||
PlanetName |
Year |
Population |
Mercury |
2000 |
40000 |
Venus |
2000 |
25 |
Earth |
2000 |
6000000000 |
Mars |
2000 |
325000 |
Jupiter |
2000 |
8426300200 |
Znock |
2000 |
550000 |
Saturn |
2000 |
1000000 |
Uranus |
2000 |
753425370 |
Neptune |
2000 |
<NULL> |
Pluto |
2000 |
<NULL> |
Mercury |
2001 |
35000 |
Venus |
2001 |
3 |
Earth |
2001 |
6500000000 |
Mars |
2001 |
326000 |
Jupiter |
2001 |
8426300202 |
Znock |
2001 |
8700 |
Saturn |
2001 |
75000 |
Uranus |
2001 |
844360002 |
Neptune |
2001 |
<NULL> |
Pluto |
2001 |
<NULL> |
Looking at all the rows that refer to Venus, you'll notice there are two. You can see that in the year 2000 there were 25 Venusians on Venus, but in 2001 there were only 3 of them left. I guess the volcanoes wiped them out.
Don't confuse database tables with spreadsheets. While it's true that spreadsheets can show data in a way that looks like the tables above, the way they work with the data is quite different. |
There are many different databases around the world: Microsoft Access, Oracle, DB2, Microsoft SQL Server, Informix, mySQL and so the list goes on. So how do you talk to a database from C#? Will they all understand what we're asking for?
The simple answer is that you use a language like C# to wrap up and send some "database language" to the database, and it decides how to fetch and send back the columns and rows that you asked for.
(To tell the truth, there is another layer in-between called ADO.NET, but we won't talk too much about that here)
Many years ago, because of all the different databases, some people got together and agreed on "one database language" that could speak to most of the databases around. That language is called Structured Query Language (SQL for short). Don’t confuse the SQL language with Microsoft’s product named SQL Server – most databases support the SQL language.
Before we talk about how to work with databases in C#, let's get familiar with the basics of the SQL language. Here follow some examples of statements written in SQL and what happens when you run them.
The three main types of actions are SELECT to view some data, INSERT to insert new data, and UPDATE to change existing data - we'll give examples of each of these.
Usually the way you write Select statements is the following:
SELECT <the Columns you want to see>
FROM <the appropriate Database Tables>
WHERE <some condition is true>
SELECT *
FROM PLANET
Brings back all rows and all columns from the table called PLANET.(The star * means all columns)
PlanetName |
DistanceFromSun |
Inhabitants |
---|---|---|
Mercury |
57909 |
Mercurians |
Venus |
108200 |
Venusians |
Earth |
149600 |
Earthlings |
Mars |
227940 |
Martians |
Jupiter |
778400 |
Jupiterians |
Znock |
7208100 |
Znockers |
Saturn |
1423600 |
Saturnians |
Uranus |
2867000 |
Uranians |
Neptune |
4488400 |
Neptunians |
Pluto |
5909600 |
Plutonians |
SELECT PlanetName, Inhabitants
FROM PLANET
Brings back just the "PlanetName" and "Inhabitants" columns for all rows in the PLANET table.
PlanetName |
Inhabitants |
---|---|
Mercury |
Mercurians |
Venus |
Venusians |
Earth |
Earthlings |
Mars |
Martians |
Jupiter |
Jupiterians |
Znock |
Znockers |
Saturn |
Saturnians |
Uranus |
Uranians |
Neptune |
Neptunians |
Pluto |
Plutonians |
SELECT PlanetName, Inhabitants
FROM PLANET
WHERE PlanetName='Venus'
Brings back just the "PlanetName" and "Inhabitants" columns for only those rows in the PLANET table which have a PlanetName of "Venus".
PlanetName |
Inhabitants |
---|---|
Venus |
Venusians |
SELECT PlanetName
FROM POPULATION
WHERE Population<100000
Brings back the PlanetName and Population, from the POPULATION table, wherever the population column has a value less than 100000.
PlanetName |
Population |
---|---|
Mercury |
40000 |
Venus |
25 |
Neptune |
<NULL> |
Pluto |
<NULL> |
Mercury |
35000 |
Venus |
3 |
Saturn |
75000 |
Neptune |
<NULL> |
Pluto |
<NULL> |
Usually the way you write Insert statements is the following:
INSERT INTO <the Database Table you want to add rows to>
(<the Columns you want to add values into>)
INSERT INTO PLANET
(PlanetName, DistanceFromSun, Inhabitants)
VALUES
('Fluff', 23500000, 'Fluffies')
Adds a new row to the PLANET table. This is actually a "silent" action - it doesn't bring back any rows to your C# program - but we show the table here so you get a picture of what's happened.
PLANET |
|
|
PlanetName |
DistanceFromSun |
Inhabitants |
Mercury |
57909 |
Mercurians |
Venus |
108200 |
Venusians |
Earth |
149600 |
Earthlings |
Mars |
227940 |
Martians |
Jupiter |
778400 |
Jupiterians |
Znock |
7208100 |
Znockers |
Saturn |
1423600 |
Saturnians |
Uranus |
2867000 |
Uranians |
Neptune |
4488400 |
Neptunians |
Pluto |
5909600 |
Plutonians |
Fluff |
23500000 |
Fluffies |
Usually the way you write Update statements is the following:
UPDATE <the Database Table you want to change>
SET <Columns you want to change> = <new values>
UPDATE PLANET
SET PlanetName='Stuff', Inhabitants='Stuffies'
WHERE PlanetName='Fluff'
Changes some of the values in the row which has a PlanetName "Fluff". We show the resulting table here, but in reality this is a "silent" action and will not bring back any rows to your C# program.
PLANET |
|
|
PlanetName |
DistanceFromSun |
Inhabitants |
Mercury |
57909 |
Mercurians |
Venus |
108200 |
Venusians |
Earth |
149600 |
Earthlings |
Mars |
227940 |
Martians |
Jupiter |
778400 |
Jupiterians |
Znock |
7208100 |
Znockers |
Saturn |
1423600 |
Saturnians |
Uranus |
2867000 |
Uranians |
Neptune |
4488400 |
Neptunians |
Pluto |
5909600 |
Plutonians |
Stuff |
23500000 |
Stuffies |
If you think about it, you will notice there is a relationship between the two tables PLANET and POPULATION above. They both have a column called "PlanetName." We say that the two tables are related on the column "PlanetName" - and that allows us to collect all the information for a particular planet
We could take, for example, all the rows that have to do with Venus, from both tables ...
PLANET
PlanetName DistanceFromSun Inhabitants
Venus108200Venusians
|
POPULATION
PlanetNameYearPopulation
Venus200025
Venus20013
|
and join them together into what appears to be one big table ...
SELECT *
FROM PLANET INNER JOIN POPULATION ON PLANET.PlanetName=POPULATION.planetName
WHERE PlanetName='Venus'
PLANETS_AND_POPULATION
PlanetName DistanceFromSun InhabitantsPlanetNameYearPopulation
Venus108200VenusiansVenus200025
Venus108200VenusiansVenus20013
|
There are reasons why programmers may want to do special things for special databases or situations. In the .NET environment, for example, there are several different ways to work with data. If you know you're using a Microsoft SQL Server database, for example, you can use special objects to send your SQL queries and because of that it will work really fast. But if you're talking to Microsoft Access, you can't use that special object.
The code differs slightly then, depending on whether you’re using SQL Server or not, and we’re not sure whether you are. So here’s what we’ve done:
The three database example programs in this section (12a, 13a and 14a) are written assuming you have got SQL Server Express installed (or one of the other SQL Server versions).
But in case you haven’t, we’ve also included, with the disk samples, a version of each that uses Microsoft Access. These are programs 12b, 13b and 14b, and they will run without needing any database setup at all.
We encourage you to install SQL Server Express at some stage though – it’s a much better database to program against. Additionally, SQL Server skills are more valued in the business world – so the sooner you get to know SQL Server the better. You can download it free from https://msdn.microsoft.com/vstudio/express/sql/download/.
If you have Microsoft SQL Server Express installed and working, use examples 12a, 13a and 14a. If you don’t, or if you have trouble getting them working, you can fall back to examples 12b, 13b and 14b instead, which do the same thing without needing a database installed. |
In the following C# examples, we'll use the SqlConnection and SqlCommand classes to communicate with the SQL Server Express sample database named “Planets”. These are the special classes for talking to any version of Microsoft SQL Server. We'll work with the data further in two different ways
Using the SqlDataReader class.
The SqlDataReader class allows you a lot of programming control since you can step through each data row yourself and choose what to do with the values you get back.
Using the SqlDataAdapter and DataSet classes.
Datasets are useful if you wish to have the data rows automatically displayed in a forms control such as a datagrid. This approach requires quite a few lines of code to get the data from the database, but saves a lot of trouble in displaying that same data - because smart controls like the DataGridView understand how to hook themselves up to a dataset.
The following program connects to a SQL Server Express database and sends it a SQL query. It then gets the results back, steps through each row and writes each PlanetName value on a new line in a Label control.
Code for program 12a (SQL Express Version – see disk example 12b for Microsoft Access version) |
|
In this next program we want to display several columns of data, which would be too messy in a Label - so we use a DataGridView.
We execute the same query as the previous program but this time put the results into a DataSet. We then hook the DataGridView to the DataSet and it automatically displays all the data.
Hooking up some invisible back-end data to a visual control is referred to as data binding.
Code for program 13a (SQL Express version – see disk example 13b for Microsoft Access version) |
|
Displaying data in a DataGridView is okay, but you’ll notice that if you change the data, it does not get saved back into the database. So let’s modify the approach to allow “two-way data binding”.
We’ll cheat a little bit here (hey, it’s called “increasing our productivity”) by not writing our own UPDATE and INSERT SQL commands – the System.Data namespace has a smart little class called CommandBuilder that can figure out how to write them itself and handles them behind the scenes.
Code for program 14a (SQL Express version – see disk example 14b for Microsoft Access version) |
|
Try modifying some values and entering new ones. Click “Save” and then close the form. If you re-run the program you will see that the data really has been updated/inserted in the database.
Those of you who do not have a version of Microsoft SQL Server installed, and have a different database you wish to talk to, will need to make a few small adjustments.
First of all, the connection string describing the database location, type, etc. must change.
A connection string for SQL Server Express may look like this:
string connectionString =
"Integrated Security=SSPI;Persist Security Info=False; Initial
Catalog=Northwind;Data Source=localhost";
or like this, if you’re connecting directly to the database file (as in this book’s examples):
string connectionString =
@"data source=.\SQLEXPRESS;Integrated Security=SSPI;
AttachDBFilename=c:\C#4#KIDS\examples\database\SqlServer\planets.mdf;
User Instance=true”;
(Because of space we’re wrapping this around to a few lines, but in this format the portion in quotes actually needs to be on one line)
A connection string for Microsoft Access could look like this:
string connectionString =
@"Provider=Microsoft.Jet.OLEDB.4.0; Data Source
c:\C#4#KIDS\examples\database\Access\planets.mdb;";
(as explained higher above, you would need to write this on one line)
Other databases will each have a particular format. You may find examples in the Visual C# Express help documentation or in the documentation that came with your database.
Beyond changing the connection string, you then also change the “Sql” classes to “OleDb” classes.
Start by including System.Data.OleDb namespace instead of the System.Data. SqlClient namespace. This contains classes that can work with a variety of databases.
using System.Data.OleDb;
Then, swap the classes you use to work with data, as follows:
SQL Server |
General Databases |
---|---|
SqlCommand |
OleDbCommand |
SqlCommandBuilder |
OleDbCommandBuilder |
SqlDataAdapter |
OleDbDataAdapter |
SqlConnection |
OleDbConnection |
The classes in System.Xml help you to work with XML data in various ways. Common tasks include:
opening an XML document
reading a piece of XML to get some specific values out
writing an XML file to disk
XML (Extensible Markup Language) is everywhere these days and you're most likely to have heard about it already. XML is a great example of a language that both people and computers can understand. While some computer systems work with data that seems to be a garbled mess to humans, XML is written in plain text and can be read by the average country bumpkin.
You might, for example, put together an XML document like the following to hold some geographical data on disk:
|
Every XML document has this first line simply so programs know there is XML coming The outermost block A nested (indented) block with information about the South American continent More deeply-nested blocks with information about two countries on the Asian continent |
It's a lot like HTML, but you're free to make up your own tag names in XML.
Let's talk about two terms you'll need to understand if you're going to read further about XML.
XML data is held inside elements. An element has a name and usually holds a value. In the example below, the element "Country" has the value "Argentina".
elementname |
elementvalue |
|
<Country> |
Argentina |
</Country> |
As you can see above, an element is represented with an opening tag and a closing tag. The closing tag must be named exactly like the opening tag, but must include a forward slash "/".
If the element has no value, it is legal to rather use just one tag and close it immediately.
elementname |
<Country /> |
But we may want to describe various special things about an element. We may, for example, want to indicate that a country has a capital city - so, as an example, we may create an attribute of our element called "capital". In the example below, the “capital” attribute of the “Country” element “Argentina” is equal to “Buenos Aires”.
elementname |
|
attributename |
|
attributevalue |
|
elementvalue |
|
<Country |
|
capital |
= |
"Buenos Aires" |
> |
Argentina |
</Country> |
All this is quite easy for us humans to read and, since there's a clear structure to it, you can imagine that computers can easily be taught to read it too. "Computer, walk through this document, when you get to a "<" you know you're about to read an element name. When you reach the next ">" then you know to look for the element's value ... and so on.
The following program reads some geographical data in from an XML file and displays it on a form.
It uses three classes from the System.Xml namespace:
XmlDocument (creates an object that can load XML data so we can work with it)
XmlNodeList (useful for holding the list of elements we read from the file)
XmlNode (holds one XML element)
It allows the user to type in something called an xPath expression to say what elements to get from the xml file. An xPath expression such as //earth/continent/country means "find all elements named "country" wherever they appear beneath an element named "continent" appearing under an element named "earth".
Code for program 15 |
|
The program shows the raw xml file in a "RichTextBox" control. Then, below the xPath expression which the user can modify, the resulting element values are shown. So once you get this program running, try changing the expression and clicking the "Get data" button.