REAL-WORLD COMPUTER PROGRAMMING FOR KIDS of ALL AGES
STEP 44: DISSECTING CODE and PROGRAMMATICALLY OPENING THE BROWSER
We ran out of space in the last Step to finish examining the code to display the contents of the DataGridView Control on the bottom half of the form, along with the image, and the code that opens a browser window with a book about the State when the image is clicked.
So, we will take up with that here and now.
Before we get into the meatier code, though, let’s take a quick look at a little bit of code that I added so that the DataGridView Control’s Click method would pseudo-fire (fire without the user actually clicking in it) when the app starts. I added this because I didn’t want the Controls at the bottom half of the form to be empty (except for the DateTimePicker displaying the current date), especially when the first row is highlighted when the app starts, which could lead to confusion in the user’s mind (“Why is there no data populated below? After all, there is a Row selected...”).
To “fool” the compiler into thinking the DataGridView Control had been clicked, I added this code to the Form’s Shown Event Handler:
private void Form1_Shown(object sender, EventArgs e)
{
const int ALASKA_ROW = 0;
var args = new DataGridViewCellEventArgs(STATE_COLUMN, ALASKA_ROW);
dataGridView1_CellContentClick(dataGridView1, args);
}
As mentioned, I added the code above to the Form’s “Shown” Event Handler. This event fires after the Form’s Load Event. If you look at the Form’s Events page in the Properties pane, you will see that there are many Events you can write code for. To see them, click on the Form (away from the Panels and what’s on them), and click the “Lightning” icon in the Properties pane in the Southeast corner of Visual Studio.
There are many Events you can write code in response to. And there’s a “tip” at the bottom that informs you when the selected Event fires.
But back to the code for the Shown Event Handler:
When the contents of a Cell are clicked, the specific cell is noted (the row and the column). We assign the Row and Column we want the app to think is clicked in the assignment to the args variable, telling it that it was the Cell at the juncture of the STATE_COLUMN (column 1) and the ALASKA_ROW (row 0 – first row). We then call the Event Handler by name, passing it the DataGridView that was supposedly clicked (dataGridView1, our DataGridView Control) and the args, which we just populated with the Cell that was supposedly clicked. That causes the Event Handler to be fired, even though the Cell was not really clicked, thus populating the Controls at the bottom of the Form. We could, of course, change it to highlight some other row first, say the Montana row, like so:
private void Form1_Shown(object sender, EventArgs e)
{
const int MONTANA_ROW = 3;
var args = new DataGridViewCellEventArgs(STATE_COLUMN, MONTANA_ROW);
dataGridView1_CellContentClick(dataGridView1, args);
}
...and then the Form would display like this on startup (after the Form’s Shown Event Handler fires, which happens so quickly that we don’t see any change occurring – we just see Montana “from the git-go”):

Now, let’s look at the rather confusingly named GetCombinedRankValueRank method, which is called by the Event Handler that fires when a Cell in the DataGridView is clicked. After that, we will examine the code attached to the PictureBox’s Click Event Handler, which causes the URL for the book shown in the image to display in your Browser – in other words, it opens that page.
So here is the GetCombinedRankValueRank method, which is called by the DataGridView when one of its Cells is clicked:
private int GetCombinedRankValueRank(int combinedRankValue)
{
try
{
conn = new MySqlConnection(connstr);
conn.Open();
try
{
DataTable dtStates = new DataTable();
MySqlCommand comm = conn.CreateCommand();
comm.CommandText = "SELECT COUNT(states_id) "+
"FROM states "+
"WHERE combinedRank < @combinedRankValue";
comm.Parameters.AddWithValue("@combinedRankValue", combinedRankValue);
return Convert.ToInt32(comm.ExecuteScalar());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
throw;
}
}
finally
{
conn.Close();
}
}
The SQL shown above is another Query (using a SELECT statement) whose related Command object calls ExecuteScalar, which means only one piece of data is returned from the Query (rather than an entire Row or multiple Rows). In this case an Integer value is returned. What the query is asking for, in plainer English, is: “Give me the number of States with a lower value than that of the current State.” The “current State”’s combinedRank value is passed to the GetCombinedRankValueRank method via the combinedRankValue argument.
For example, for Missouri, the value of the combinedRankValue argument is 60, so it’s asking how many States have a combinedRank value of less than 60 – in other words, how many States are above it in combinedRank. So it’s really asking “Which Rank does this combinedRank value have?” It’s ranking the combined rank.
Note that the value returned has to be converted to an Int32 for it to work.
The value is then concatenated (combined) with the combinedRank value to give some context to just what that value means (the user may wonder, “Is 60 “good” or “bad” or “mediocre”?”):

So we see that 60 is pretty good – Missouri is #12, in the top quarter of all States in overall “score.”
Note: The word “mediocre” is used above. This is an oft-misunderstood word. It is not synonymous with “poor” or “crummy” or suchlike pejoratives. It really basically means “average.” After all, the word (mediocre) is related to the word “medium,” which can be thought of as being “in the middle.” We are probably all mediocre at several things, but that’s not a bad thing – we’re in good company – a large company, the majority of people – when we are mediocre in the literal meaning of the word (as opposed to the popular perceived meaning of the word).
PROGRAMMATICALLY OPENING THE BROWSER
There is one more bit of code to look at: how to open the browser to a specific page. We want the user to be able to click the image in the PictureBox Control and have the amazon page for that book to open in a Browser window for them.
Sound complicated/complex/convoluted? Do you think it will take a bunch of mind-bending code to accomplish this amazing feat? Actually no, it’s pretty simple. See for yourself:
private void pictureBox1_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start(currentBookURL);
}
One line of code!
But wait – where does this “currentBookURL” variable come from?
We’ve seen it before. It is declared at the start of the Form’s code:
public partial class Form1 : Form
{
MySqlConnection conn;
string connstr = "server=127.0.0.1;user id=root;password=gr8OoglyMoogly;persistsecurityinfo=True;database=statesdb";
const int STATE_COLUMN = 1;
string currentBookURL = string.Empty;
...and assigned when a Cell in the DataGridView is clicked:
if (dataGridView1.Rows[e.RowIndex].Cells[STATE_COLUMN].Value != null)
{
. . .
currentBookURL = dataGridView1.Rows[e.RowIndex]. Cells[BOOKURL_COLUMN].Value.ToString();
}
So we assign the value of the current book’s URL when the Row is clicked and hold that string value in readiness, just in case the user clicks the Image displayed in the PictureBox Control.
This is what opens in the Browser if the user clicks the “Pennsylvania” image:

This is a rather short Step, but the next thing to show you is how to allow the user to update the states Table, specifically the haveResidedThere, haveVisited, and notes columns, and if we started in on that now we would have to break off in the middle of it, so I am leaving that until the next Step.
So ... until then!
Note: Oh, but wait! An odd word (to a normal person, that is to say a non-programmer) was used above, namely “concatenate.” This is one of those words that is used a lot in programming. It simply means “combined.” But not in the mathematical sense. For example, “60” concatenated with “12” is not 72, but rather what you see in the screen shot showing Missouri as the current State above – the string “60” followed by the string “12”
Every discipline has its own characteristic jargon, and programming is no exception there. “Concatenate” is just one of those words which you will see and hear quite often if you continue your involvement with programming.
All right, I mean it this time – see you in the next Step!
Earth-shakingly Important Notice: If you have a basic programming question (suitable to an audience of “Kids”), send it to idiolectable@gmail.com, specifying whether you would like your name and location used if it is printed in a future “Step” of this newsletter. If you are a subscriber to the newsletter, you can also leave a question at the bottom of this Step, in the “Comments” section.
If you do not want to give your real name, a nickname is acceptable (the first “Letter to the Editor” of mine that was printed appeared in Rolling Stone magazine, back in the early 1970s, and I signed it “Sylvester” for some reason which I no longer remember).
Finally, it’s always interesting to see where people are from, so please provide your City or Town and the State it’s in, too (or Province, or whatever the region where you live is called).
To listen to this Step, the audio of it can be found here: