tag:blogger.com,1999:blog-56748267083862284152024-02-20T00:47:53.130-08:00C# For Dummies v2You will find everything for learning C# hereUnknownnoreply@blogger.comBlogger114125tag:blogger.com,1999:blog-5674826708386228415.post-89138849899385084412014-03-12T12:26:00.001-07:002014-03-12T12:26:37.380-07:00Dates and Times in C# .NET<div dir="ltr" style="text-align: left;" trbidi="on">
At some stage of your programming career, you'll need the ability to manipulate
dates and time. A typical example would be a database programme where you want
to record when an entry was made, especially if it's an order for a product.
Or if you want to, say, calculate how many days it's been since an order was
placed.<br />
Start a new project for this. Add a button to your new form, and double click
it to get at the code.<br />
An inbuilt structure you can use to manipulate dates is called DateTime. Add
this to you button code:<br />
<div class="indent_big">
DateTime theDate;</div>
<div class="indent_big">
theDate = DateTime.Now;</div>
<span class="indent_big">MessageBox.Show( theDate.ToString() );</span><br />
<br />
After setting up a DateTime variable called <b>theDate</b>, we have this line:<br />
<div class="indent_big">
theDate = DateTime.Now;</div>
The <b>Now</b> property returns the current system date and time of your computer,
wherever you are in the world.<br />
The third line in our code converts the DateTime into a string and then displays
it in a message box. When the code is run, and the button clicked, the message
box will be something like this:<br />
<div align="center">
<img alt="Message Box with a Date and Time" height="154" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/dates/message_box1.gif" width="168" /></div>
This is the date in UK format (day first, then month), followed by the current
time (hours, minutes and seconds).<br />
You can also have this, instead of Now:<br />
<div class="indent_big">
theDate = DateTime.Today;</div>
And even this<br />
<div class="indent_big">
theDate = DateTime.UtcNow;</div>
Utc is something called Coordinated Universal Time, or International Atomic
Time. <br />
Try all three in your code and see how they differ.<br />
To get at just the year, or the month, or the day, take a look at the IntelliSense
list when you type the dot after DateTime:<br />
<br />
<div align="center">
<img alt="A list of Date and Time Methods and Properties in C#" height="878" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/dates/date_time_list.gif" width="500" /></div>
If you click on Day to highlight it, you'll see that it is an Integer:<br />
To use this, then, you can set up a new integer variable and hand it the day:<br />
<div class="indent_big">
theDate = DateTime.UtcNow;</div>
<div class="indent_big">
int theDay = theDate.Day;</div>
The Month and Year are also Integers, so the code is similar:<br />
<div class="indent_big">
int theMonth = theDate.Month;</div>
Or<br />
<div class="indent_big">
int theYear = theDate.Year;</div>
You can also convert your date to a string, and use something called a Format
Provider. Try this code:<br />
<div class="indent_big">
DateTime theDate = DateTime.UtcNow;</div>
<div class="indent_big">
string custom = theDate.ToString("d");</div>
<div class="indent_big">
MessageBox.Show(custom);</div>
When you run your programme and click the button, the date displays in this
format:<br />
<div align="center">
<b>12/11/13</b></div>
Change the "d" in the code above to "D" (capital D instead
of lowercase). When you run the code, the date is displayed like this:<br />
<div align="center">
<b>12 November 2013</b></div>
Here's a list of letters you can use, and what they will display. Try a few
and see for yourself:<br />
<div align="center">
<img alt="A Table of Date and Time formats in C# .NET" height="257" src="http://www.homeandlearn.co.uk/csharp/images/extras/datesTable.gif" width="332" /></div>
Another thing you can do with DateTime is to specify a format. Type the following:<br />
<div class="indent_big">
DateTime firstDate = new DateTime</div>
After the final "e", type a round bracket. You should see this:<br />
<div align="center">
<img alt="The DateTime Class in C#" height="62" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/dates/date_time_brackets.gif" width="402" /></div>
There are 12 different ways to use the DateTime structure. Each one is giving
you the option of a date/time format. Examine option 4 of 12:<br />
<div align="center">
<img alt="Specify a Date" height="97" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/dates/date_time_brackets2.gif" width="787" /></div>
You can just type some numbers here:<br />
<div class="indent_big">
DateTime firstDate = new DateTime(2013, 01, 14);</div>
What you'll get back is the Date you specified. But you'll also get the time
as a series of zeros:<br />
<div align="center">
<img alt="A date displayed in a message box" height="154" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/dates/message_box2.gif" width="168" /></div>
If you want to calculate the difference between one date and another, then
a more precise structure is used with DateTime - TimeSpan. Here's how to use
it:<br />
<div class="indent_big">
DateTime firstDate = new DateTime(2013, 01, 14);<br />
DateTime secondDate = DateTime.Parse("1 Feb 2013");</div>
<div class="indent_big">
TimeSpan dateDiff;<br />
dateDiff = secondDate.Subtract(firstDate);<br />
MessageBox.Show("Date diff:" + dateDiff.ToString() );</div>
The first line sets up a date: the 14th of January 2013. The second line sets
up a date in a different way:<br />
<div class="indent_big">
DateTime secondDate = DateTime.Parse("1 Feb 2013");</div>
After the dot of DateTime, we're using <b>Parse</b>. In between the round brackets
of Parse, simply type your date between double quotes.<br />
When you subtract one date from another, the answer is returned as a TimeSpan
structure. This uses similar methods and properties as DateTime. One of the
options is Subtract:<br />
<div class="indent_big">
TimeSpan dateDiff;<br />
dateDiff = secondDate.Subtract( firstDate );</div>
After typing a date then a dot, use the Subtract method. In between the round
brackets of Subtract, you need another date - the one you're trying to subtract.
When the code is run, it will calculate the difference between the two dates.<br />
You can also add date and time values to ones you already have. Examine this
code:<br />
<div class="indent_big">
firstDate = firstDate.AddDays(30);<br />
MessageBox.Show( firstDate.ToString("D") );</div>
Now we're using AddDays after our firstDate variable. In between the round
brackets of AddDays, type how many days you want to add.<br />
When the IntelliSense list appears, have a look at other date and time values
you can add: AddMonths, AddYears, etc.<br />
</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5674826708386228415.post-30606795321333903732014-03-12T12:25:00.003-07:002014-03-12T12:25:41.266-07:00Getting at the values on other Forms<div dir="ltr" style="text-align: left;" trbidi="on">
Turn your Form2 into a Change Case dialogue box, just like ours below:<br />
<div align="center">
<img alt="A Change Case form" height="300" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/forms/form_change_case3.gif" width="300" /></div>
When the OK button is clicked, we want the text in the text box on Form1 to
change case, depending on which of the three options was chosen.<br />
The problem we face is that the text box is private to Form1, and can't be
seen from outside it. If you tried to refer to the text box from Form2, you'd
just get errors.<br />
One solution is to set up a public static variable, of type TextBox. You then
assign textBox1 to this new variable.<br />
So add the following to Form1:<br />
<div class="indent_big">
public static TextBox tb = new TextBox();</div>
This creates a new TextBox object called <b>tb</b>. Add the line just under
your Form variable, and your coding window will look like this:<br />
<div align="center">
<img alt="C# code to create a new text box" border="1" height="170" src="http://www.homeandlearn.co.uk/csharp/images/extras/formTB.gif" width="419" /></div>
Notice that we've deleted the message box code, and went back to the original.
That's because we don't need the message box anymore. Delete yours as well.<br />
Now that we have a TextBox object, we can assign our text box on form one to
it. In the Form Load event of Form1, add the following line:<br />
<div class="indent_big">
tb = txtChangeCase;</div>
(The easiest way to bring up the code stub for the Form Load event is to double
click a blank area of the form in design view.)<br />
Here's what all the Form1 code looks like now:<br />
<div align="center">
<img alt="Form Load Event" border="1" height="329" src="http://www.homeandlearn.co.uk/csharp/images/extras/formTB2A.gif" width="444" /></div>
When the main form (Form1) loads, the text box will now be available to Form2.<br />
So double click your OK button on Form2 to bring up its code stub. Enter the
following:<br />
<div class="indent_big">
string changeCase = Form1.tb.Text;</div>
We're setting up a string variable called changeCase. The contents of this
new string variable will be the Text from the text box called tb on Form1.<br />
To change the case of the text, we can use string methods for two of them:
Uppercase and Lowercase. Like this:<br />
<div class="indent_big">
changeCase = changeCase.ToUpper();</div>
<div class="indent_big">
changeCase = changeCase.ToLower();</div>
Unfortunately, C# .NET does not have a direct string method to change text
to Proper Case (or Title case as it's also know). Proper Case is capitalising
the first letter of each word. For example, "This Is Proper Case".<br />
In order to get Proper Case, you have to reference two System namespaces. One
called Globalization and one called Threading. Add the following to the very
top of the coding window:<br />
<div class="indent_big">
using System.Globalization;<br />
using System.Threading;</div>
The code window will then look something like this:<br />
<div align="center">
<img alt="Add two using statements" border="1" height="224" src="http://www.homeandlearn.co.uk/csharp/images/extras/properCase.gif" width="277" /></div>
Now that we have these two references, the next thing to do is to set up something
called a CultureInfo object:<br />
<div align="center">
<b>CultureInfo properCase = Thread.CurrentThread.CurrentCulture;</b></div>
The CurrentCulture tells you information about the various language options
of your particular country. Our CultureInfo object is called properCase.<br />
That's not the end of it, though! You also need a TextInfo object:<br />
<div align="center">
<b>TextInfo textInfoObject = properCase.TextInfo;</b></div>
It's this TextInfo object that has the methods we need. We're setting up a
TextInfo object called textInfoObject. We're handing it the TextInfo property
of our properCase CultureInfo object.<br />
Finally, we can change the case:<br />
<div align="center">
<b>changeCase = textInfoObject.ToTitleCase( <i>changeCase</i>
);</b></div>
The TextInfo object has a method called ToTitleCase. In between the round brackets
of the method, you type what it is you want to convert.<br />
Hopefully, in future versions of C#, they'll add an easier way to convert to
Proper Case!<br />
To get which of the options on our Form2 was chosen, we can add a series of
if … else statements:<br />
<div align="center">
<img alt="C# code to change case" border="1" height="307" src="http://www.homeandlearn.co.uk/csharp/images/extras/properCase3.gif" width="494" /></div>
So we're just checking to see which radio button was selected. We're then doing
the case conversion.<br />
To put the changed text into the text box on Form1, add the following line:<br />
<div align="center">
<b>Form1.tb.Text = changeCase;</b></div>
Add the line just before your DialogResult line. The full code for the button
should be this<br />
<div align="center">
<img alt="Full C# code for form 2" border="1" height="409" src="http://www.homeandlearn.co.uk/csharp/images/extras/properCase2.gif" width="503" /></div>
Run your programme and test it out. Click your button to bring up Form2. Select
the Upper Case option and then click your OK button. You should find that the
text in txtChangeCase on your main form will now be in uppercase.<br />
<br />
The next section of the C# course deals with Dates and Times.</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5674826708386228415.post-1223428228501165012014-03-12T12:25:00.001-07:002014-03-12T12:25:17.107-07:00Modal Forms in C# .NET<div dir="ltr" style="text-align: left;" trbidi="on">
Return to the code for your button. Instead of using the Show method, change
it to this:<br />
<div class="indent_big">
secondForm.<i>ShowDialog</i>();</div>
The method we're now using is ShowDialog. This creates what's known as a Modal
form. A Modal form is one where you have to deal with it before you can continue.
Run your programme to test it out. Click the button and a new form appears.
Move it out of the way and try to click the button again. You won't be able
to.<br />
Modal forms have a neat trick up their sleeves. Add two buttons to your blank
second form. Set the following properties for them:<br />
<div class="indent_big_no_bold">
<b>Name</b>: btnOK<br />
<b>Text</b>: OK</div>
<div class="indent_big_no_bold">
<b>Name</b>: btnCancel<br />
<b>Text</b>: Cancel</div>
Your second form will then look like this:<br />
<div align="center">
<img alt="A Modal Form" height="300" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/forms/form_change_case2.gif" width="300" /></div>
Double click the OK button and add the following:<br />
<div class="indent_big">
this.DialogResult = DialogResult.OK;</div>
After you type the equals sign, the IntelliSense list will appear. Select DialogResult
again, then a dot. The IntelliSense list will then show you this:<br />
<div align="center">
<img alt="DialogResult Value" height="263" src="http://www.homeandlearn.co.uk/csharp/images/extras/dialogResult.gif" width="213" /></div>
Select OK. What this does is to record the result of the button click, and
set it to OK.<br />
Double click your Cancel button and add the following code:<br />
<div class="indent_big">
this.DialogResult = DialogResult.Cancel;</div>
It's the same code, except we've chosen Cancel as the Result. Your coding window
for form 2 should look like this:<br />
<div align="center">
<img alt="DialogResult Code" border="1" height="184" src="http://www.homeandlearn.co.uk/csharp/images/extras/dialogResult_code.gif" width="408" /></div>
You can use Form1 to get which of the buttons was clicked on Form2. Was it
OK or was it Cancel?<br />
Change the button code on Form1 to this:<br />
<div align="center">
<img alt="C# code to detect if the OK button was clicked" border="1" height="134" src="http://www.homeandlearn.co.uk/csharp/images/extras/dialogResult_code2.gif" width="408" /></div>
The code checks to see if the OK button was clicked. If so, it displays a message.
We'll get it to do something else in a moment. But you don't have to do anything
with the Cancel button: C# will just unload the form for you.<br />
Try it out. Click your <b>Change Case</b> button on Form1. When your new form
appears, click the OK button. You should see the message. Try it again, and
click the Cancel button. The form just unloads.</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5674826708386228415.post-48479976893796620522014-03-12T12:24:00.001-07:002014-03-12T12:24:46.889-07:00Creating Multiple Forms in C# .NET<div dir="ltr" style="text-align: left;" trbidi="on">
There aren't many programmes that have only one form. Most programmes have
other forms that are accessible from the main one that loads at start up. In
this section, you'll learn how to create programmes with more than form.<br />
The programme we'll create is very simple one. It will have a main form with
a text box and a button. When the button is clicked, it will launch a second
form. On the second form, we'll allow a user to change the case of the text
in the text box on form one.<br />
Here's what form one looks like:<br />
<div align="center">
<img alt="Change Case Form" height="280" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/forms/form_change_case.gif" width="281" /></div>
Design the above form. Set the Name property of the text box to <b>txtChangeCase</b>.
For the Text property, add some default text, but all in lowercase letters.
Set the Name property of the button to <b>btnFormTwo</b>.<br />
Adding a new form to the project is easy. Click Project from the menu bar at
the top of the Visual C# software. From the Project menu, select <b>Add New
Windows Form</b>. You'll see the <b>Add New Item</b> dialogue box appear. Make
sure Windows Form is selected. For the Name, leave it on the default of<b> Form2.cs</b>.
When you click OK, you should see a new blank form appear:<br />
<div align="center">
<img alt="Form Tabs in Visual C# .NET" border="1" height="24" src="http://www.homeandlearn.co.uk/csharp/images/extras/formTabs.gif" width="236" /></div>
It will also be in the Solution Explorer on the right:<br />
<div align="center">
<img alt="A second form showing in the Solution Explorer" height="252" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/forms/solution_explorer.gif" width="295" /></div>
Adding the form to the project is the easy part - getting it to display is
an entirely different matter!<br />
To display the second form, you have to bear in mind that forms are classes.
When the programme first runs, C# will create an object from your Form1 class.
But it won't do anything with your Form2 class. You have to create the object
yourself.<br />
So double click the button on your Form1 to get at the coding window.<br />
To create a Form2 object, declare a variable of Type <b>Form2</b>:<br />
<div class="indent_big">
Form2 secondForm;</div>
Now create a new object:<br />
<div class="indent_big">
secondForm = new Form2();</div>
Or if you prefer, put it all on one line:<br />
<div class="indent_big">
Form2 secondForm = new Form2();</div>
What we've done here is to create a new object from the Class called Form2.
The name of our variable is secondForm.<br />
To get this new form to appear, you use the Show( ) method of the object:<br />
<div class="indent_big">
secondForm.Show();</div>
Your code should now look like this:<br />
<div align="center">
<img alt="C# code to create a second form" border="1" height="102" src="http://www.homeandlearn.co.uk/csharp/images/extras/form1_code.gif" width="411" /></div>
Run your programme and test it out. Click your button and a new form should
appear - the blank second form.<br />
However, there's a slight problem. Click the button again and a new form will
appear. Keep clicking the button and your screen will be filled with blank forms!<br />
To stop this from happening, move the code that creates the form outside of
the button. Like this:<br />
<div align="center">
<img alt="C# code to Show the form" border="1" height="112" src="http://www.homeandlearn.co.uk/csharp/images/extras/form1_code2.gif" width="409" /><br />
</div>
Try your programme again. Click the button and you won't get lots of forms
filling the screen.<br />
In the next lesson, you'll learn what a Modal form is.</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5674826708386228415.post-48202933514891462412014-03-12T12:23:00.003-07:002014-03-12T12:23:58.829-07:00Update a Record, Delete a record<div dir="ltr" style="text-align: left;" trbidi="on">
<h3>
Update a Record</h3>
Sometimes, all you want to do is to update a record in the database, change
a name, for example, or amend an address. <br />
Add a new button to your form. Call it <b>btnUdate</b>. Double click the button
to get at the code. Add the following lines:<br />
<div class="indent_big">
DataRow row = ds.Tables[0].Rows[inc];</div>
<div class="indent_big">
row[1] = txtFirstName.Text;<br />
row[2] = txtSurname.Text;<br />
row[3] = txtJobTitle.Text;<br />
row[4] = txtDepartment.Text;</div>
This is very similar to the code for adding a new record. Again we start by
creating a DataRow object. This time, we place a specific row in the new object.
That row is one from the DataSet:<br />
<div class="indent_big">
ds.Tables[0].Rows[ inc ];</div>
However, this is the old row. The new details are in the textboxes, the ones
you may have amended. To place the new details into the new row object, we simply
transfer the textbox date to a position in the row object:<br />
<div class="indent_big">
row[1] = txtFirstName.Text;<br />
row[2] = txtSurname.Text;<br />
row[3] = txtJobTitle.Text;<br />
row[4] = txtDepartment.Text;</div>
All we need to do now is to make a call to the <b>UpdateDatabase</b> method
from our class. Again, we can do this in a <b>try … catch</b> block:<br />
<div class="indent_big">
try<br />
{</div>
<div class="indent_bigger">
objConnect.UpdateDatabase(ds);</div>
<div class="indent_bigger">
MessageBox.Show("Record Updated");</div>
<div class="indent_big">
}<br />
catch (Exception err)<br />
{</div>
<div class="indent_bigger">
MessageBox.Show(err.Message);</div>
<div class="indent_big">
}</div>
The only line we really need is this one:<br />
<div class="indent_bigger">
objConnect.UpdateDatabase(ds);</div>
This is the same as before: we're just passing our UpdateDatabase method the
name of the DataSet, which is called <b>ds</b>.<br />
The whole of the <b>btnUpdate</b> code is this:<br />
<div align="center">
<img alt="C# code to update a record in a database table" height="353" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/database_connect/code_button_update.gif" width="413" /></div>
Try it out. Run your form and amend one of the records. Click your Update button.
When you close the form down and open it back up again, the amended record will
display.<br />
<br />
<h3>
Delete a Record</h3>
To delete a record from the Dataset, you use the <b>Delete</b> method on the
DataSet:<br />
<div class="indent_big">
ds.Tables[0].Rows[inc].Delete( );</div>
This is enough to Delete the entire Row ( <b>Rows[inc]</b> ). But it is only
deleted from the Dataset. To delete if from the underlying database as well,
we can call our <b>UpdateDatabase</b> method again.<br />
<div class="indent_big">
objConnect.UpdateDatabase(ds);</div>
Because a row has been deleted, we need to change the value of our <b>MaxRows</b>
variable. We also need to deduct 1 from the <b>inc</b> variable, and make a
call <b>NavigateRecords</b>:<br />
<div class="indent_big">
MaxRows = ds.Tables[0].Rows.Count;<br />
inc--;</div>
<div class="indent_big">
NavigateRecords();</div>
Add another button to your form. Call it <b>btnDelete</b>. Here's the whole
of the code to add to your new button:<br />
<br />
<div align="center">
<img alt="C# code to delete a record from a database table" height="327" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/database_connect/code_button_delete.gif" width="414" /></div>
Try it out. Run your form. Navigate to a record you want to delete, then press
your Delete button. Close your form and reopen it. The record you delete should
be gone.<br />
<br />
<b>Exercise P</b><br />
Examine this version of our form:<br />
<div align="center">
<img alt="The completed C# database form" height="590" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/database_connect/form_record_number_ex.gif" width="426" /></div>
If you look at the bottom, you'll see a label that says <b>Record 1 of 10</b>.
Implement this in your own programme. If you set up a method, you can just call
it from <b>NavigateRecords</b>.<br />
<section id="Wrapper"><article><section>
<div align="right">
<br /></div>
</section></article></section>
<div align="right">
<section> </section></div>
<section>
<div align="right">
<br /></div>
<div align="left">
OK, that's enough of databases! It's a huge subject, obviously,
and many books have been written on the subject. We've only touched the surface
in these lessons, and encourage you to delve deeper. Especially if you want
a job as a programmer!</div>
<div align="left">
In the next section, we'll take a look at multiple forms.</div>
</section></div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5674826708386228415.post-35274988686854140572014-03-12T12:23:00.001-07:002014-03-12T12:23:17.722-07:00Add a Record to the Dataset and Update the Database<div dir="ltr" style="text-align: left;" trbidi="on">
When you add a new record, you'll want to add it to the Dataset and the underlying
database. Let's see how. <br />
Add three new buttons to the form. Set the following properties for your buttons:<br />
<div class="indent_big_no_bold">
<b>Name</b>: btnAddNew<br />
<b>Text</b>: Add New</div>
<div class="indent_big_no_bold">
<b>Name</b>: btnSave<br />
<b>Text</b>: Save<br />
<b>Enabled</b>: False</div>
<div class="indent_big_no_bold">
<b>Name</b>: btnCancel<br />
<b>Text</b>: Cancel<br />
<b>Enabled</b>: False</div>
The Add New button won't actually add a new record. We'll use this button to
clear the textboxes, ready for a new record to be added. We can also disable
this button after it has been clicked, and enable the Save and Cancel buttons.
The Save button is where we'll add the record to the Dataset and to the Database.<br />
Double click your Add New button, and add code to clear the text boxes:<br />
<div class="indent_big">
textBox1.Clear();<br />
textBox2.Clear();<br />
textBox3.Clear();<br />
textBox4.Clear();</div>
If the user clicks the Add New button then we want to disable it, and then
switch on the Save and Cancel button. To do that, here's the code:<br />
<div class="indent_big">
btnAddNew.Enabled = false;<br />
btnSave.Enabled = true;<br />
btnCancel.Enabled = true;</div>
That's all we need to do here. You can test it out, if you want. When the form
loads it will look like this (we've put our buttons on a GroupBox):<br />
<div align="center">
<img alt="C# form showing Add New Record button" height="449" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/database_connect/form_load_add_record.gif" width="426" /></div>
When you click the Add New button, the form will look like this:<br />
<div align="center">
<img alt="C' form - saving a new record to the database" height="449" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/database_connect/form_load_add_record2.gif" width="426" /></div>
But all the code does is to clear the four textboxes of text. The user can
then enter a new record.<br />
Return to Design Time and double click your Cancel button. What we need to
do here is to call <b>NavigateRecords</b>. We need to do this because the textboxes
are all blank. Calling NavigateRecords will put the record that was erased back
into the textboxes.<br />
The Cancel button also needs to reset all three buttons. Here's the code to
add, then:<br />
<div class="indent_big">
NavigateRecords( );</div>
<div class="indent_big">
btnCancel.Enabled = false;<br />
btnSave.Enabled = false;<br />
btnAddNew.Enabled = true;</div>
You can test it out. Click your Add New button when the form loads. The textboxes
will go blank, and the first record will disappear. Now click Cancel. You should
find that the record reappears.<br />
<br />
<h3>
Saving a New Record</h3>
After a new record has been entered into the text boxes, we can save it. Double
click your Save button to get at the code.<br />
To save a record, you need to do two things: save it to the Dataset, and save
it to the underlying database. You need to do it this way because the Dataset
with its copy of the records is disconnected from the database. Saving to the
Dataset is NOT the same as saving to the database.<br />
To add a record to the Dataset, you need to create a new Row:<br />
<div class="indent_big">
DataRow row = ds.Tables[0].NewRow( );</div>
This creates a new DataRow object that we've called <b>row</b>. The DataRow
object is used to add new rows to a Dataset. But the new row will not have any
data. To add data to the row, the format is this:<br />
<div class="indent_big">
row[1] = textFirstName.Text;</div>
So after your DataRow variable (<b>row</b>) you need a pair of square brackets.
In between the square brackets type its position in the Row. This is the Column
number. So <b>row[1] </b>refers to the <b>first_name</b> column, for us. After
an equals sign, you type whatever it is you want to add to that Column - the
text from <b>textFirstName</b>, in our case.<br />
Finally, you issue the Add command:<br />
<div class="indent_big">
ds.Tables[0] Rows.Add( row );</div>
After <b>Add</b>, and in between a pair of round brackets, you type the name
of the row you want to add, which was <b>row</b> in our example. The new row
will then get added to the end of the Dataset.<br />
So add this code to your Save button:<br />
<div class="indent_big">
DataRow row = ds.Tables[0].NewRow( );<br />
row[1] = txtFirstName.Text;<br />
row[2] = txtSurname.Text;<br />
row[3] = txtJobTitle.Text;<br />
row[4] = txtDepartment.Text;</div>
<div class="indent_big">
ds.Tables[0].Rows.Add(row);.Rows.Add(row);</div>
To actually update the database, we need to add a new method to our class.
This method will use the <b>DataAdapter</b> we set up. The DataAdapter is linked
to the database itself, and can issue Update, Insert and Delete commands. It's
quite easy to do and only takes a couple of lines.<br />
If your DatabaseConnections class is not open, double click it in the Solution
Explorer to get at the code. Now add the following method:<br />
<div class="indent_big_no_bold">
public void <b>UpdateDatabase</b>( <b>System.Data.DataSet
ds</b> )<br />
{</div>
<div class="indent_big">
}</div>
So this is a <b>public</b> method that doesn't return a value (<b>void</b>).
We called it <b>UpdateDatabase</b>. In between the round brackets of UpdateDatabase
have a look at what the code is:<br />
<div class="indent_big">
System.Data.DataSet ds</div>
This is a DataSet being passed to the method. The name of the DataSet is <b>ds</b>.
Our DataSet, remember, is where all the records are kept, even the ones that
have changed. We'll be updating the database with these new changes.<br />
In order to do an automatic update, you need something called a <b>CommandBuilder</b>.
This is initialised with the name of a DataAdapter, the DataAdapter we set up
earlier in the Class.<br />
Add this rather long line to your method (it should be on one line in your
code): <br />
<div class="indent_small">
System.Data.SqlClient.SqlCommandBuilder cb = new System.Data.SqlClient.SqlCommandBuilder(
da_1 );</div>
We've called our CommandBuilder <b>cb</b>. At the end, in between round brackets,
we have the name of our DataAdapter, which was <b>da_1</b>.<br />
Now that we have a CommandBuilder, we can do something with it. Add this line
to your method:<br />
<div class="indent_big">
cb.DataAdapter.Update( ds.Tables[0] );</div>
The CommandBuilder has a property called <b>DataAdapter</b>. This property
has a method of its own called <b>Update</b>. The Update method takes the name
of a DataSet and a table. The DataSet for us is <b>ds</b>, which is the one
we passed in to our UpdateDatabase method when we set it up. After a dot, you
type the name of a table in your dataset. <br />
Here's what your method should look like:<br />
<div align="center">
<img alt="C# code for a CommandBuilder object" height="122" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/database_connect/code_class_update_method.gif" width="701" /></div>
And that's it. That's enough to update the underlying database with your new
record. Of course, we have yet to call our new method into action.<br />
Go back to the code for your Save button. Add a <b>try … catch</b> statement:<br />
<div class="indent_big">
try<br />
{</div>
<div class="indent_big">
}<br />
catch (Exception err)<br />
{</div>
<div class="indent_bigger">
MessageBox.Show(err.Message);</div>
<div class="indent_big">
}</div>
For the try part, add the following:<br />
<div class="indent_big">
try<br />
{</div>
<div class="indent_bigger">
objConnect.UpdateDatabase(ds);</div>
<div class="indent_bigger">
MaxRows + 1;<br />
inc = MaxRows - 1;</div>
<div class="indent_bigger">
MessageBox.Show("Database updated");</div>
<div class="indent_big">
}</div>
As the first line of the try part, we have this:<br />
<div class="indent_big">
objConnect.UpdateDatabase(ds);</div>
Here, we access our DatabaseConnections object (<b>objConnect</b>), and call
our new method <b>UpdateDatabase</b>. In between the round brackets of our UpdateDatabase
method we have the name of our DataSet, which is <b>ds</b>. This contains all
the records we pulled from the database, and any amendments we've made. We're
handing the whole thing over to the new method, where the CommandBuilder and
DataAdapter will take care of the updates for us.<br />
Notice the next two lines:<br />
<div class="indent_bigger">
MaxRows = MaxRows + 1; <br />
inc = MaxRows - 1;</div>
Because we have added a new Row to the Dataset, we also need to add 1 to the
<b>MaxRows</b> variable. The <b>inc</b> variable can be set to the last record
in the Dataset, which is <b>MaxRows - 1</b>.<br />
The final three lines of our Save code are these:<br />
<div class="indent_big">
btnCancel.Enabled = false;<br />
btnSave.Enabled = false;<br />
btnAddNew.Enabled = true;</div>
These three lines just reset the buttons to their original state.<br />
The whole of the code for your Save button should look like this:<br />
<div align="center">
<img alt="C# code - saving a new record to a database" height="448" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/database_connect/code_save_button.gif" width="402" /></div>
Try it out. When you start your programme, click the Add New button to clear
the textboxes. Enter a new record in the blank textboxes and then click your
Save button. Click your Previous and Next buttons. You'll see that the new record
appears. When you close down your project and open it up again, the new record
should still be there.<br />
(If the new record doesn't appear when you restart, go back to Design Time.
In the Solution Explorer, click on your Database under Resources to select it.
Now have a look at the Properties window below the Solution Explorer. Locate
a property called <b>Copy to Output Directory</b>. It has three settings: <b>Do
not copy</b>, <b>Copy always</b>, and <b>Copy if newer</b>. If your database
is not updating, try either <b>Copy if newer </b>or <b>Copy always</b>.)<br />
In the next lesson, you'll learn how to update a record, and how to delete
a record.</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5674826708386228415.post-62084351122749161542014-03-12T12:22:00.001-07:002014-03-12T12:22:40.045-07:00Moving Forward and Backward through the Database<div dir="ltr" style="text-align: left;" trbidi="on">
To move forward through the database table, add a button to your form. Give
it the Name <b>btnNext</b>. Add some text to the button.<br />
Double click your button to get at the coding window. For the code, we need
to check what is inside of the <b>MaxRows</b> variable and make sure we don't
go past it. MaxRows, remember, is holding how many records are in the DataSet.
We also need to increment the <b>inc</b> variable. It is this variable that
will move us on to the next record.<br />
Add the following if statement to your button:<br />
<div align="center">
<img alt="C# code to move forward through the database" border="1" height="200" src="http://www.homeandlearn.co.uk/csharp/images/sqlExpress/navigateNext.gif" width="397" /></div>
The first line of the If Statement says "If <b>inc</b> does not equal
<b>MaxRows</b> minus 1". If it doesn't then we increment the <b>inc</b>
variable and call <b>NavigateRecords</b>. But can you see why we need to say<b>
MaxRows - 1</b>? It's because of the <b>Rows[inc]</b> line in our <b>NavigateRecords</b>
method. The count for Rows starts at zero. So if we only have 4 records in the
database, the count will be for 0 to 3. MaxRows, however, will be 4. If we don't
deduct 1, the programme will crash with an error: <b>IndexOutOfRange</b>.<br />
If MaxRows is reached, then we can display a message for the user: "No
more rows".<br />
Run your programme and test it out. You should be able to move forward through
your database. Here's what your form should look like when the last record is
reached:<br />
<div align="center">
<img alt="C# form showing the last record in the database" height="321" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/database_connect/form_last_record.gif" width="409" /></div>
<br />
<h3>
Move Backwards through the Database</h3>
We can use similar code to move backwards through the records in the database.<br />
Add another button to your form. Change the Text property to <b>Previous Record</b>.
Change the Name property to <b>btnPrevious</b>.<br />
Double click your new button to get at the coding window. Now add the following:<br />
<div class="indent_big">
if (inc > 0)<br />
{</div>
<div class="indent_bigger">
inc--;<br />
NavigateRecords( );</div>
<div class="indent_big">
}<br />
else<br />
{</div>
<div class="indent_bigger">
MessageBox.Show("First Record");</div>
<div class="indent_big">
}</div>
The if statement is now only checking the <b>inc</b> variable. We need to check
if it's greater than zero. If it is, we can deduct 1 from <b>inc</b>, and then
call our <b>NavigateRecords</b> methods. When the form loads, remember, <b>inc</b>
will be 0. So if we tried to move back one record after the form first loads
the programme would crash. It would crash because we'd be trying to access <b>Rows[-1]</b>.<br />
Run your programme and test it out. Click you Previous button and you should
see this:<br />
<div align="center">
<img alt="C# form showing the first record in the database" height="370" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/database_connect/form_first_record_button.gif" width="426" /></div>
<br />
<h3>
Jump to the Last Record in your Database</h3>
To move to the last record of your database, you only need to make sure that
the <b>inc</b> variable and <b>MaxRows</b> have the same value.<br />
Add a new button to your form. Set the Text property as <b>Last Record</b>,
and the Name property as <b>btnLast</b>. Double click the button, and add the
following code:<br />
<div class="indent_big">
if (inc != MaxRows - 1)<br />
{</div>
<div class="indent_bigger">
inc = MaxRows - 1;<br />
NavigateRecords( );</div>
<div class="indent_big">
}</div>
The If Statement again checks that <b>inc</b> is not equal to <b>MaxRows</b>
minus 1. If it isn't, we have this:<br />
<div class="indent_bigger">
inc = MaxRows - 1;</div>
MaxRows minus 1 would equal 3 in a four record database. Because <b>Rows[inc]</b>
goes from 0 to 3, this is enough to move to the last record after the call to
NavigateRecords. <br />
<br />
<h3>
Jump to the First Record in your Database</h3>
To move to the first record in the database, we only need to set inc to zero.<br />
Add another button to your form. Change the Text property to First Record.
Change the Name property to btnFirst. Double click your new button and add the
following code:<br />
<div class="indent_big">
if (inc != 0)<br />
{</div>
<div class="indent_bigger">
inc = 0;<br />
NavigateRecords( );</div>
<div class="indent_big">
}</div>
This just checks to see if inc isn't already zero. If it isn't, we set the
inc variable to 0. Then we call the NavigateRecords method.<br />
Run your programme and test it out. You should now be able to move through
the records in your database without the programme crashing. What we'll do now
is to allow the user to add a new record to the database. This is more complex
than the navigation, so you may need to pay close attention!</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5674826708386228415.post-75880496052618648032014-03-12T12:21:00.003-07:002014-03-12T12:21:56.343-07:00Using the Database Connection Class<div dir="ltr" style="text-align: left;" trbidi="on">
You now have a Windows form and a Database class that you created yourself.
Go back to the form and add four textboxes. Change the Name property of each
textbox to the following:<br />
<div align="center">
<b>txtFirstName<br />
txtSurname<br />
txtJobTitle<br />
txtDepartment</b></div>
Add four labels to your form and place them next to the textboxes. Add the
following text to the labels:<br />
<div align="center">
<b>First Name<br />
Surname<br />
Job Title<br />
Department</b></div>
Your form will then look something like this:<br />
<div align="center">
<img alt="C# Form with four textboxes" height="335" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/database_connect/form_textboxes_labels.gif" width="409" /></div>
What we're going to do now is to connect to the database using our class. We'll
do this from the Form Load event. We'll place the first record from the table
into the textboxes. Once this is done, we can then add buttons that will allow
is to scroll forwards and backwards through all the records in the table.<br />
To add the Form Load code stub, simply double click anywhere on your form that
is not a textbox or a label. The code stub that opens up will look like this:<br />
<div align="center">
<img alt="C# code showing form load event" height="410" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/database_connect/code_form_load.gif" width="450" /></div>
Because we're going to be adding buttons later, we need to set up variables
where all the buttons can see them. The first one we need is a variable to store
our connection object. Add the following line just outside of the Form Load
event:<br />
<div class="indent_big">
DatabaseConnection objConnect;</div>
The variable is called <b>objConnect</b>. It is of type <b>DatabaseConnection</b>,
which is the name of our class.<br />
We also need a string to hold our connection string from the Setting page we
set up earlier. So add this, as well:<br />
<div class="indent_big">
string conString;</div>
This is just a normal string variable that we've called <b>conString</b>. <br />
Your coding window should now look like this:<br />
<div align="center">
<img alt="Two field variables added to the form" height="259" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/database_connect/code_form_load_vars.gif" width="442" /></div>
We also need a <b>DataSet</b> object. This is because the <b>GetConnection</b>
method in our class is set up to load all the database data into a DataSet.
When we call our GetConnection method we'll need somewhere to put the DataSet,
which will be another DataSet. So add this line to your code, just below the
other two:<br />
<div class="indent_big">
DataSet ds;</div>
A DataSet contains rows, which correspond to a row in the database table. To
manipulate each row, you work with a <b>DataRow</b> object. You'll see how this
works shortly. But add this line to your code, as well:<br />
<div class="indent_big">
DataRow dRow;</div>
The final two variables we need to add outside of the form load event are these
two:<br />
<div class="indent_big">
int MaxRows;<br />
int inc = 0;</div>
The two variables are both integers. The first one, MaxRows, will tell us how
many rows there are in the DataSet, which is how many rows were pulled from
the database table. The other integer variable, inc, will be used to move from
one record to another, and back again. We'll need this for the buttons we'll
add later.<br />
But your coding window should now look like this:<br />
<div align="center">
<img alt="A C~ try ... catch statement" height="346" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/database_connect/code_form_load_try.gif" width="393" /></div>
We can now turn our attention to the Form Load event. We'll place the code
for this event in a try … catch statement. So add the following to your
form load event:<br />
<div class="indent_big">
try<br />
{</div>
<div class="indent_big">
}<br />
catch (Exception err)<br />
{</div>
<div class="indent_bigger">
MessageBox.Show(err.Message);</div>
<div class="indent_big">
}</div>
Your code window should look like this:<br />
<div align="center">
<img alt="More field variables" height="346" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/database_connect/code_form_load_try.gif" width="393" /></div>
The first thing to do in the try part is to set up an object from our class.
Here's the line that does that:<br />
<div class="indent_big">
objConnect = new DatabaseConnection( );</div>
This creates a new object for us, of type <b>DatabaseConnection</b>. (Don't
forget the round brackets on the end.)<br />
We can now grab that connection we set up in the Settings page earlier. To
do that, start with your conString variable then an equal sign:<br />
<div class="indent_big">
conString =</div>
After the equal sign, type the word <b>Properties</b>, then a dot. As soon
as you type the dot, you'll see the IntelliSense list appear:<br />
<div align="center">
<img alt="Accessing C# settings via code" height="121" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/database_connect/code_form_load_try2.gif" width="554" /></div>
Select <b>Settings</b> (which refers to the Settings page), then type another
dot. You'll see the IntelliSense list again:<br />
<div align="center">
<img alt="Accessing C# settings via code, the Default property" height="156" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/database_connect/code_form_load_try3.gif" width="600" /></div>
Select <b>Default</b>, and type another dot:<br />
<div align="center">
<img alt="Accessing C# settings, the connection string" height="258" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/database_connect/code_form_load_try4.gif" width="791" /></div>
You should see your connection string on the list, which was <b>EmployeesConnectionString</b>
for us. Select this and then end the line with a semicolon.<br />
Now that we've placed the connection string into our <b>conString</b> variable,
we can hand it over to our class. Type <b>objConnect</b> (the name of our class
object in the Form), then a dot. You should see this:<br />
<div align="center">
<img alt="Accessing a property in our Database class" height="278" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/database_connect/code_form_load_try5.gif" width="545" /></div>
Our <strong>connection_string</strong> property is showing up on the IntelliSense list. This
allows us to pass over the connection string to our DatabaseConnection class.<br />
Finish the line by adding the conString variable:<br />
<div class="indent_big">
objConnect.connection_string = conString;</div>
The next thing we need to do is to pass over some SQL to our DatabaseConnection
class. We set this up on the Settings page. The SQL was this:<br />
<div class="indent_big">
SELECT * FROM tbl_employees</div>
This reads "Select all the records from the table called tbl_employees".<br />
Add the following line to your code:<br />
<div class="indent_big">
objConnect.Sql = Properties.Settings.Default.SQL;</div>
You should see the IntelliSense list appear as you're typing the above line.
At the end, is the name of the setting we added - <b>SQL</b>. This all gets
passed to our DatabaseConnection class via the Sql property before the equal
sign.<br />
What we've done so far is to hand our <b>DatabaseConnection</b> class a connection
string, which contains the name and location of the database; and we've also
handed it some SQL, so that we can pull records from a table in the database.
We set up a method in our DatabaseConnection class that takes these two values
(connection string and SQL), and uses them to place data from the database into
a DataSet. Let's now add code to return that DataSet.<br />
The name of our DataSet in the Form code is <b>ds</b>. This is the variable
we set up at the top of the Form Load event. We can call our <b>GetConnection</b>
method from the DatabaseConnection class and hand its DataSet over to the variable
ds. Add this code:<br />
<div class="indent_big">
ds = objConnect.GetConnection;</div>
So <b>objConnect</b> is our object created from the DatabaseConnection class.
Type a dot and you'll see the IntelliSense list appear:<br />
<div align="center">
<img alt="Accessing a method in our Database class" height="313" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/database_connect/code_form_load_try6.gif" width="555" /></div>
The <b>GetConnection</b> method is on the list. Double click to add it to your
code, and then type a semicolon to end the line.<br />
We can count how many records are in the DataSet. (These are the same records
that are in the database table, remember.) You do it like this:<br />
<div class="indent_big">
MaxRows = ds.Tables[0].Rows.Count;</div>
MaxRows is the integer variable we set up at the top of the Form Load event.
After an equal sign, we have this:<br />
<div class="indent_big">
ds.Tables[0].Rows.Count;</div>
The name of our DataSet is <b>ds</b>. The DataSet has a property called <b>Tables</b>.
This is a list of all the tables in your DataSet. (We only have one table.)
The first table is at position 0. The 0 goes between square brackets. After
a dot, you type <b>Rows.Count</b>. This counts how many rows are in the DataSet.<br />
To fill the textboxes, we can add a method. Let's call it <b>NavigateRecords</b>:<br />
<div class="indent_big">
private void NavigateRecords()<br />
{</div>
<div class="indent_big">
}</div>
We don't need to return a value so the method is set up as <b>void</b>.<br />
Because we want to access one row at a time, we can use the DataRow object
we set up earlier. If you wanted to access row 1 from the DataSet, the code
would be this:<br />
<div class="indent_big">
dRow = ds.Tables[0].Rows[1];</div>
Here, the entire first row will be placed in the <b>dRow</b> variable. To place
this first row into the textboxes we can use the <b>ItemArray</b> property of
DataRow objects. The ItemArray property has a method called <b>GetValue</b>.
In between the round brackets of GetValue you type the column you want to access.
For example, take this code:<br />
<div class="indent_big">
txtFirstName.Text = dRow.ItemArray.GetValue(1).ToString();</div>
The value in between the round brackets of <b>GetValue</b> is 1. This will
place row 1, column 1 into the textbox called <b>txtFirstName</b>. If we then
advanced the row counter to 2, row 2 column 1 will be placed into the textbox.
Advanced the row counter again and row 3 column 1 will end up in the textbox.
(The ToString at the end just ensures that any non-text values get converted
to strings.)<br />
To advance the row counter, we can use our <b>inc</b> variable:<br />
<div class="indent_big">
dRow = ds.Tables[0].Rows[inc];</div>
So instead of hard-coding a value of 1 between Rows, we're using whatever value
is inside of the <b>inc</b> variable. We can then increment the <b>inc</b> variable
later from buttons on the form. <br />
So add the following code, just below the Form Load event:<br />
<div class="indent_small">
private void NavigateRecords()<br />
{</div>
<div class="indent_big">
dRow = ds.Tables[0].Rows[inc];</div>
<div class="indent_big">
txtFirstName.Text = dRow.ItemArray.GetValue(1).ToString();<br />
txtSurname.Text = dRow.ItemArray.GetValue(2).ToString();<br />
txtJobTitle.Text = dRow.ItemArray.GetValue(3).ToString();<br />
txtDepartment.Text = dRow.ItemArray.GetValue(4).ToString();</div>
<div class="indent_small">
}</div>
Now add a call to NavigateRecords from your Form Load event:<br />
<div class="indent_big">
MaxRows = ds.Tables[0].Rows.Count;</div>
<div class="indent_big">
NavigateRecords( );</div>
The whole of your code should now look like this:<br />
<div align="center">
<img alt="C# code to load a database record into textboxes" height="667" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/database_connect/code_navigate_records.gif" width="556" /></div>
You can try out your code, now. Run our programme and you should find that
the first record from the database table appears in your textboxes:<br />
<div align="center">
<img alt="C# form showing the first record from our database" height="310" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/database_connect/form_first_record.gif" width="409" /></div>
In the next lesson, you'll add some buttons to the form so that you can scroll
forwards and backwards through all the records in the databas table.</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5674826708386228415.post-57117899359451984702014-03-12T12:21:00.001-07:002014-03-12T12:21:24.064-07:00Creating a Database Connection Class<div dir="ltr" style="text-align: left;" trbidi="on">
In order to connect to our database, we can create a class to handle all the
connection issues. <br />
From the Project menu at the top of Visual Studio, select <b>Add Class</b>:<br />
<div align="center">
<img alt="Project > Add Class menu in Visual Studio" height="368" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/project_add_class.gif" width="335" /></div>
You'll see the following dialogue box appear:<br />
<div align="center">
<img alt="The Add New Item dialogue box" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/project_add_class2_new.gif" /></div>
Make sure the <b>Class</b> item is selected. In the <b>Name</b> box at the
bottom, type <b>DatabaseConnection.cs</b>. Then click the <b>Add</b> button
at the bottom.<br />
When you click Add, your new class will appear in the Solution Explorer on
the right:<br />
<div align="center">
<img alt="A new class showing in the Solution Explorer" height="258" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/sol_explorer_class.gif" width="295" /></div>
The code stub for your class will be open in the main window (if it's not,
simply double click DatabaseConnection in the Solution Explorer):<br />
<div align="center">
<img alt="Code stub for a new C# NET class" height="248" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/class_code.gif" width="282" /></div>
(2010 users won't have the Threading.Tasks using statement.)<br />
The class we're going to create, as its name suggests, will help us to connect
to a database. We'll add fields, properties and methods to the class.<br />
The first thing to do is to set up two field variables:<br />
<div class="indent_big">
private string sql_string;<br />
private string strCon;</div>
Add the two lines above to your class code and it will look like this<br />
<div align="center">
<img alt="C# Code showng two field variables" height="164" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/class_code2.gif" width="273" /></div>
The <b>sql_string</b> field variable will hold a SQL string like "SELECT
* FROM table". We'll get this from the Settings we set up earlier. The
<b>strCon</b> field variable will hold a location of the database. Again, we'll
get this from the Settings we added.<br />
The next code to add is a write-only property (meaning it has no get part):<br />
<div class="indent_big">
public string Sql<br />
{</div>
<div class="indent_bigger">
set { sql_string = value; </div>
<div class="indent_big">
}</div>
We've called this property <b>Sql</b>. It's going to be a <b>string</b>. It's
<b>public</b> because we want to access this property from outside of this class.
The <b>value</b> (the SQL itself) will be assigned to the <b>sql_string</b>
field variable. We're saying, set the variable called <b>sql_string</b> to whatever
is held in the <b>Sql</b> variable on line one.<br />
The next bit of code sets something into the strCon field variable. This something
is our connection string, the one we set up on the Settings page. Again, this
is a write-only property.<br />
<div class="indent_big">
public string connection_string<br />
{</div>
<div class="indent_bigger">
set { strCon = value; }</div>
<div class="indent_big">
}</div>
When you've added the two properties above, your code should look like this:<br />
<div align="center">
<img alt="C# code showing two properties" height="317" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/class_code3.gif" width="305" /></div>
The next thing we need is something called a <b>DataSet</b>. Think of a DataSet
as a grid that holds the data from our table. Each row in the DataSet grid will
hold a row from our database table. The table is then closed, and the rows and
columns in the DataSet is manipulated with code. In other words, you load table
data into a DataSet, rather than manipulate the table in the database. <br />
Add this code to you class:<br />
<div class="indent_big">
public System.Data.DataSet GetConnection<br />
{</div>
<div class="indent_bigger">
get { return MyDataSet( ); }</div>
<div class="indent_big">
}</div>
We've called this property <b>GetConnection</b>. This is a read-only property.
For the get part we're calling a method with the name <b>MyDataSet</b>. The
method connects to the database and fills a Dataset. It's this method that does
all the work. Here's the code stub to add:<br />
<div class="indent_big">
private System.Data.DataSet MyDataSet( )<br />
{</div>
<div class="indent_big">
}</div>
The method is called <b>MyDataSet</b>. Instead of it being a string or an integer
it's of this type:<br />
<div class="indent_big">
System.Data.DataSet</div>
So the type is <b>DataSet</b>. The inbuilt DataSet code lives in <b>System.Data</b>.<br />
The first line to add to the new method is this rather long line:<br />
<div class="indent_small">
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(
strCon );</div>
The variable we've created is called <b>con</b>. This variable is of type <b>SqlClient.SqlConnection</b>.
Again, the SqlClient.SqlConnection code lives in <b>System.Data</b>. We're creating
a new object of this type. In between the round brackets of <b>SqlConnection</b>
we have our <b>strCon</b> variable. So SqlConnection will use our connection
string in strCon to connect to the database.<br />
The next line to add is this:<br />
<div class="indent_big">
con.Open( );</div>
Here, we open a connection to the database.<br />
However, although we have opened a connection to the database, we haven't yet
opened the table in the database. To do that, we need something called a <b>DataAdapter</b>.
A DataAdapter is used to open up a table in a database. We'll need to reference
this DataAdapter later in our project, so we'll need to add a new line to the
top of the Class. Add the following line just below the <b>sql_string</b> and
<b>strCon</b> variables:<br />
<div class="indent_big">
private string sql_string;<br />
private string strCon;<br />
System.Data.SqlClient.SqlDataAdapter da_1;</div>
The variable we've set up is called <b>da_1</b>. It's of type <b>SqlClient.SqlDataAdapter</b>.<br />
Go back to your MyDataSet method and add this line:<br />
<div class="indent_big">
da_1 = new System.Data.SqlClient.SqlDataAdapter(sql_string,
con);</div>
In between round brackets we have our <b>sql_string</b> variable. This is used
to tell C# which records we want from the table. (We're going to be passing
it that Settings string we added earlier.) After a comma, you need a connection
object. This tells C# which database the table is in.<br />
The next line is this:<br />
<div class="indent_big">
System.Data.DataSet dat_set = new System.Data.DataSet( );</div>
This sets up a <b>DataSet</b> object. The variable we've created is called
<b>dat_set</b>. The whole method is going to be returning this DataSet, which
will hold all the records from the table.<br />
The final three lines are these:<br />
<div class="indent_big">
da_1.Fill(dat_set, "Table_Data_1");</div>
<div class="indent_big">
con.Close( );</div>
<div class="indent_big">
return dat_set;</div>
The first of those lines uses the <b>Fill</b> method of our DataAdapter object.
This is used to fill a DataSet. In between the round brackets of Fill you need
the name of a DataSet to fill. After a comma, you can add a name for the Fill,
if you want. We've added one called <b>Table_Data_1</b>.<br />
The final two lines close the connection object, and return the DataSet.<br />
The whole of the code for your class should look like this:<br />
<div align="center">
<img alt="C# code showing a new method added to the class" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/class_code_all2.gif" /></div>
Save your work and we'll put this new class to use.</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5674826708386228415.post-82096709674556699682014-03-12T12:20:00.001-07:002014-03-12T12:20:20.259-07:00Creating a Database Project with C# .NET<div dir="ltr" style="text-align: left;" trbidi="on">
What we're going to do now is to use the Employees database we created in the
previous section. We'll add it as a resource to a new project. We can then create
a form with buttons that allow us to scroll back and forward through the records
in the database. If you didn't manage to create a database then you can use
ours. You'll find the Employees database in the extra files here on our site:
<a href="http://www.homeandlearn.co.uk/downloads/downloads.html" target="_blank">extra files</a>.<br />
<h3>
<br />
Adding a Database to a Project</h3>
Create a new project. Call it <b>EmployeesDatabase</b>. To add a database to
your new project, have a look at the Solution Explorer on the right. Locate
the Properties item:<br />
<br />
<div align="center">
<img alt="Solution Explorer, Properties item" height="252" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/sol_explorer_properties.gif" width="295" /></div>
Double click on properties to see a new screen appear. Click on the Resources
tab on the left of the new screen:<br />
<div align="center">
<img alt="Resources tab" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/resources_tab_new.gif" /></div>
Click on the <b>Add Resource</b> dropdown list at the top and select <b>Add
Existing File</b>:<br />
<div align="center">
<img alt="Add a resource to a C# NET project" height="133" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/resources_tab_add.gif" width="361" /></div>
When you click on Add Existing File, you'll see a standard Open File dialogue
box appear. Navigate to where you saved your <b>Employees.mdf </b>database.
(If you didn't create a database, navigate to the one you downloaded from our
extra files, here: <a href="http://www.homeandlearn.co.uk/downloads/downloads.html" target="_blank">extra
files</a>.) Click <b>Open</b> on Open File dialogue box.<br />
When you click Open, you'll see a Data Source Configuration screen appear,
if you have Visual Studio Express 2010 or 2010. (2013 users won't see this screen.)
Select Dataset and then click the Next button at the bottom. You should then
see a Choose Your Database Objects screen. Select Tables, and type a new <b>DataSet</b>
name at the bottom. Type <b>ds_employees</b>:<br />
<div align="center">
<img alt="Data source configuration wizard" height="513" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/data_config_wizard.gif" width="668" /></div>
Click on Finish to return to the Resources screen. All VS users will then see
this:<br />
<div align="center">
<img alt="Database added as a resource to a C# NET project" height="234" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/resources_tab_database.gif" width="671" /></div>
The database has been added to the project. You can see that it has been added
by looking at the Solution Explorer on the right.<br />
Have a look at the Properties screen again. Now click on the <b>Settings</b>
tab, just below <b>Resources</b>. If you have version 2010 or 2012 of Visual
Studio Express, you'll see this:<br />
<div align="center">
<img alt="The settings tab" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/setting_tab2.gif" /></div>
A Name, a Type, a Scope and a Value have been filled in for you. The Value
is the connection string needed when we connect to the database. The Name will
show up in the IntelliSense list a little later. For VS 2010 and 2012 users,
you can now scroll down this page a bit, until you come to the section All Visual
Studio Users.<br />
However, 2013 users won't see any entries on the Settings page. You'll have
to fill them out for yourself. To do that, click into the Name box and type
<b>EmployeesConnectionString</b>. From the Type dropdown list select <b>Connection
String</b>. Change the Scope to <b>Application</b>. For the Value, click inside
the long text box. You'll see a button to the right:<br />
<div align="center">
<img alt="Addng a connection string setting" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/setting_tab2_2013.gif" />
</div>
Click the button to see this dialogue box:<br />
<div align="center">
<img alt="Connection properties" height="415" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/connection_properties_db.gif" width="393" /></div>
The default Data Source is for an Access database, so we need to change this.
Click the Change button to see a new dialogue box:<br />
<div align="center">
<img alt="Change data source to a SQL Server database" height="301" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/connection_properties_db2.gif" width="518" /></div>
Select the option <b>Microsoft SQL Server Database File</b>, and then click
OK to go back to the previous screen.<br />
You now need to browse for your MDF database. So click the Browse button to
see an Open File dialogue box. Navigate to your project folder (the <b>EmployeesDatabase</b>
project that you have open). Double click your Resources folder to see your
database:<br />
<div align="center">
<img alt="Browsing for the Employees database" height="426" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/connection_properties_db3.gif" width="680" /></div>
Click on Open and you'll get back to the Connection Properties dialogue box:<br />
<div align="center">
<img alt="Testing the database connection" height="415" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/connection_properties_db4.gif" width="393" /></div>
Click OK (or click Test Connection first, if you want), and you'll get back
to the Settings screen. Take a look at your Value text box:<br />
<div align="center">
<img alt="Connection string" height="56" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/setting_tab_2013_value.gif" width="596" /></div>
This is a connection string we can use to connect to the Employees.mdf database.
Because we've added it as setting, we don't need to type out the full string
above.<br />
<br />
<h3>
All Visual Studio users</h3>
To gain access to the table in the database, you need something called a SQL
String. This takes the form SELECT * FROM tbl_employees. The * symbol means
"All records". There's quite a lot you can do with SQL as a language.
For our purposes, though, we just want all the data from the database, so we
can use a SELECT ALL statement.<br />
Rather than typing the SQL statement in our code, we can add it as a setting.
We can then retrieve this settings quite easily.<br />
On the Settings tab, then, click in the Name text box, the one just below <b>EmployeesConnectionString</b>.
Type <b>SQL</b>. For the Type, leave it on <b>string</b>. Change the Scope to
<b>Application</b>. For the Value, type the following:<br />
<div align="center">
<b>SELECT * FROM tbl_employees</b></div>
Your Settings page will then look like this:<br />
<br />
<div align="center">
<img alt="A SQL statement added as a setting" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/setting_tab2_sql.gif" /></div>
Save your work and close the Properties page. We can now make a start with
coding our database project.</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5674826708386228415.post-70902057624510049552014-03-12T12:19:00.003-07:002014-03-12T12:19:44.621-07:00Adding Data to a SQL Server Database Table - VS Express 2010 to 2012<div dir="ltr" style="text-align: left;" trbidi="on">
To add entries to your SQL Server database in Visual Studio Express 2010 and
2012, right click on your table name in the Database explorer. From the menu
that appears, select <b>Show Table Data</b>:<br />
<div align="center">
<img alt="Show Table Data menu" height="251" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2012/chapter_databases/db_explorer_table_show.gif" width="422" /></div>
<div align="center">
<img alt="Data entry screen" height="78" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2012/chapter_databases/table_data_fill_1.gif" width="553" /></div>
All our Column names are there, waiting to be filled in. To enter data, simply
click inside a cell and start typing.<br />
Click inside the <b>first_name</b> column. (The ID Column will take care of
itself.) Type a first name. Click inside of <b>last_name</b> and type a last
name. Click inside of <b>job_title</b> and enter a job title. Then enter the
department. You can enter the same details as ours, if you prefer (all made
up):<br />
<div align="center">
<img alt="Entering data into a table field" height="78" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2012/chapter_databases/table_data_fill_2.gif" width="553" /></div>
Notice the warning symbols in the cells. These appear when the cell data has
changed. The ID is still NULL in the image above. When we click in the next
row, however, notice that a number will appear in the first ID cell (screenshot
from Visual Studio 2012):<br />
<div align="center">
<img alt="An incremented ID field" height="65" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2012/chapter_databases/table_data_fill_3.gif" width="540" /></div>
The reason it does this is because we set <b>Is Identity</b> to <b>True</b>,
and the<b> Identity Increment</b> to 1 - it's an Auto Increment field, in other
words.<br />
But we have now created one row in our database table. Fill out a few more
rows. You can use the same details as ours, in the image below:<br />
<div align="center">
<img alt="10 records entered into a table" height="263" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2012/chapter_databases/table_data_fill_4.gif" width="547" /></div>
Don't worry if your numbers for the ID column are not sequential (are not 1
to 10). If you make a mistake and delete a Row, you are given the next number
after the deleted Row, and not the next number in your sequence.<br />
Save your work, and you will have created your very first SQL Server Express
database! But it's a huge subject, and whole books have been written about SQL
Server. We can only touch on the very basics here. What we do have, though,
is a database we can open with C# .NET programming code. We'll do that next.
</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5674826708386228415.post-22528279320065376592014-03-12T12:19:00.001-07:002014-03-12T12:19:05.609-07:00Create a Database Table - VS Express 2013 users<div dir="ltr" style="text-align: left;" trbidi="on">
<section id="Wrapper"><article><section>When you click Add New Table
in Visual Studio Express 2013, you'll see this screen appear in the middle:<br />
<div align="center">
<img alt="Adding a database table in Visual Studio Express 2013" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/table_designer2.gif" /></div>
The first thing we can do is to give the table a name. In the bottom half of
the screen above, delete the word Table between the square brackets. Type the
name tbl_employees instead:<br />
<div class="indent_small_no_bold">
<b>CREATE TABLE</b> [dbo].[tbl_employees]</div>
Now click the <b>Update</b> button, which is top left of the table designer:<br />
<br />
</section></article></section>
<div align="center">
<img alt="Setting an ID field in Visual Studio Express 2013" height="122" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/table_designer_update.gif" width="446" /></div>
You should then see the following screen:<br />
<div align="center">
<img alt="Updating the changes to the table" height="376" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/table_designer_update2.gif" width="524" /></div>
Click <b>Update Database</b> to return to the table designer. We can now set
up the columns that are going into the table.<br />
The first column name, <b>Id</b>, has already been set up:<br />
<div align="center">
<img alt="Data types for the ID Field" height="122" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/columns_pk.gif" width="502" /></div>
The Data Type is OK on <b>int</b>, which is short for Integer. The column has
a key symbol to the left, which means it is the Primary Key. This is OK, too.
The Allow Nulls is unchecked, which is what you want for a Primary Key. This
means you can't have duplicate item for this column.<br />
One thing we can do for the Id column is to have it update itself automatically.
When you add a new item to the database, the next integer in the sequence will
be added to the Id column. To set the Id column to Auto Increment, highlight
the Id row then take a look at the properties area bottom right. Expand the
<b>Identity Specification</b> item:<br />
<div align="center">
<img alt="Auto Increment property" height="381" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/columns_is_identity.gif" width="287" /></div>
Now set <b>Is Identity</b> to <b>True</b>:<br />
<div align="center">
<img alt="Identity Specification" height="381" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/columns_is_identity2.gif" width="287" /></div>
The Identity Increment has a default of 1, meaning 1 will get added to the
Id column every time a new entry is added to the table.<br />
With the Id column set up, we can add more columns.<br />
Click in the <b>Name</b> box just below Id at the top of your table designer.
Now type the new column heading <b>first_name</b>. We want this to be text.
So for the <b>Data Type</b>, select nvarchar(50), meaning a maximum of 50 characters:<br />
<div align="center">
<img accesskey="The nvarchar data type" height="463" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/columns_data_type.gif" width="446" /></div>
The <b>Allow Nulls </b>is ok checked.<br />
Add a third column by clicking into the Name box again. This time, type <b>last_name</b>.
Set the Data Type to nvarchar(50), just as before. Leave Allow Nulls checked.<br />
We only need two more columns, <b>job_title</b> and <b>department</b>. Add
this using the same technique as above. When you're done, your table designer
will look like this:<br />
<div align="center">
<img alt="All fields up set in the table" height="218" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/columns_done.gif" width="502" /></div>
Again, click the Update button to save your changes. Now have a look at the
Database Explorer on the left. You should find that your new columns are displayed:<br />
<div align="center">
<img alt="Database Explorer showing the table in Visual Studio 2013" height="346" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/db_explorer_tables_columns.gif" width="297" /></div>
Now that we have all the columns set up, we can add some data to the table.<br />
To add data to your table, right click the name of your table in the Database
Explorer. Then click <b>Show Table Data</b>:<br />
<div align="center">
<img alt="Show Table Data" height="275" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/table_data_show.gif" width="466" /></div>
When you click on <b>Show Table Data</b> you'll see a new screen appear in
the middle. This one:<br />
<div align="center">
<img alt="Add a row to the database table" height="94" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/table_data_entry.gif" width="542" /></div>
The columns are the ones we set up earlier. Each row will be a single entry
in the table.<br />
Because we set the Id column to Auto Increment, it means we don't have to type
anything into this box. So click into the text box under <b>first_name</b>.
Enter <b>Adara</b>. Now press the Tab key on your keyboard. You'll be taken
to the next text box to the right, the <b>last_name</b> field. Enter <b>Hussein</b>
as the last name. Press the Tab key again to go to the <b>job_title</b> text
box. Enter <b>Lead Programmer</b> here. Tab across again to the <b>department</b>
text box and enter <b>IT</b>. Your screen will then look like this:<br />
<div align="center">
<img alt="The first table row added" height="114" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/table_data_entry2.gif" width="542" /></div>
As you can see, there are red warning circles on the previous three entries.
This is because the data hasn't been committed to the table. To get rid of the
warning circles simply tab to the next row down. Tab to the first_name field
again, on row two this time. (You can also just click inside a text box.)<br />
Now enter the following data in your table:<br />
<br />
<div align="center">
<img alt="The data for your table" height="195" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/table_data.gif" width="451" /></div>
When you're finished, your table data screen should look like this:<br />
<div align="center">
<img alt="Table Designer showing all the data" height="274" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/table_data_entry3.gif" width="564" /></div>
Now that you have a database with some data in it, we can move on. Before you
close this solution, remember where you saved it to, and the name of your project.
If you left everything on the defaults when you installed Visual Studio, then
your projects will be in your Documents folder. The database will be in the
folder created for this database project.<br />
Save your work, and you will have created your very first Compact SQL Server
Express database! But it's a huge subject, and whole books have been written
about SQL Server. We can only touch on the very basics here. What we do have,
though, is a database we can open with C# .NET programming code. We'll do that
next.</div>
Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-5674826708386228415.post-43890085385449785482014-03-12T12:18:00.001-07:002014-03-12T12:18:26.121-07:00How to Create Tables in your SQL Server Database<div dir="ltr" style="text-align: left;" trbidi="on">
Now that you have created the database itself, you need to create at least
one table to go in it. <br />
To create a table, right click on the database in the Solution Explorer. From
the menu that appears, select <b>Open</b>:<br />
<br />
<div align="center">
<img alt="Open a database from the Solution Explorer" height="376" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/sol_explorer_mdf_open.gif" width="432" /></div>
When you click Open, you'll see the Database Explorer appear on the left hand
side of your screen:<br />
<div align="center">
<img alt="The Database Explorer in Visual Studio" height="251" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/db_explorer_database.gif" width="297" /></div>
To create a new table, right click on <b>Tables</b>. From the menu that appears,
select <b>Add New Table</b>:<br />
(In Visual Studio Express 2010, you may get an error message along the lines
of "This server version is not supported. Only servers up to Microsoft
SQL Server 2008 are supported." If you do, you'll need the SQL Server Data
Tools from here:<br />
<div align="center">
<a href="http://msdn.microsoft.com/en-us/jj650014" target="_blank">http://msdn.microsoft.com/en-us/jj650014</a></div>
If you still get no joy creating tables in your database after downloading
the SQL Server Data Tools then you can use our database. You'll find the Employees
database in the extra files here on our site: <a href="http://www.homeandlearn.co.uk/downloads/downloads.html" target="_blank">extra
files</a>. You can add it as a resource later.)<br />
<br />
When you click on Add New Table you should see the table designer open up in
the centre of your screen. This will be a different designer, depending on which
version of Visual Studio Express you have. For VS Express 2013 users, click
here to go to your section:<br />
<div align="center">
<a href="http://www.homeandlearn.co.uk/csharp/csharp_s12p3.html">Visual Studio Express 2013 continue
here</a></div>
For VS express 2010 and 2012 users, when you click <b>Create Table</b> or <b>Add
New Table</b>, you'll see a dialogue box appear. This one:<br />
<div align="center">
<img alt="Create a table in Visual Studio 2010, 2012" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/new_table2.gif" /></div>
This screen is where you set up the Columns that go in the table. You'll get
to enter the actual data later. But you need to tell SQL Server what kind of
data (Data Type) is going into each column.<br />
First, though, type a name for your table in the Name box at the top. Call
the table <b>tbl_employees</b>.<br />
For the first column in the table, type ID in the in the Column Name box. You'll
then see some more information appear:<br />
<div align="center">
<img alt="Setting up an ID field in the database table" height="141" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2012/chapter_databases/new_table_2.gif" width="663" /></div>
We'll set the ID column as a Primary Key. Click into the <b>Primary Key</b>
box and select <b>Yes</b> from the dropdown list:<br />
<div align="center">
<img alt="Setting a Primary Key" height="92" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2012/chapter_databases/new_table_3.gif" width="78" /></div>
For the other values, set the <b>Data Type</b> to <b>int</b>, the <b>Length</b>
to 4, <b>Allow Nulls</b> to <b>No</b>, and <b>Unique</b> to <b>Yes</b>. Your
first column should then look like this:<br />
<div align="center">
<img alt="ID Field properties" height="75" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2012/chapter_databases/new_table_4.gif" width="656" /></div>
The Primary Key field, the ID column, will need to have a new integer assigned
every time a new entry is added to the table. In other databases, this is known
as an auto increment number. So that this happens automatically without us having
to worry about it, have a look at the bottom of your Table screen. You should
see a Properties area. Click on <b>Identity</b> and set it to <b>True</b>:<br />
<div align="center">
<img alt="Setting an Auto Increment option" height="161" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2012/chapter_databases/new_table_5.gif" width="641" /></div>
The Increment value is set to 1, meaning the database itself will automatically
add 1 when a new record is added.<br />
Using the same technique as above, create the following Column Names, Data
Types, Length Allow Nulls, Unique and Primary Key values:<br />
<div align="center">
<img alt="The fields in the database table" height="137" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2012/chapter_databases/new_table_6.gif" width="557" /></div>
If you're not too sure about database terminology by the way, here are what
all those headings and values mean:<br />
<div class="indent_small_no_bold">
<b>Data Type</b> - This is the kind of data going
into a table column. The ID column can only have intergers, while all the others
can only have text (nvarchar). </div>
<div class="indent_small_no_bold">
<b>Length</b> - How many characters or digits
the field can hold.</div>
<div class="indent_small_no_bold">
<b>Allow Nulls</b> - A Null value is one where
nothing is set for that field, not even a zero or a blank string.</div>
<div class="indent_small_no_bold">
<b>Unique</b> - This means whether or not you
can have duplicate values in this field</div>
<div class="indent_small_no_bold">
<b>Primary Key</b> - This is used for things like
linking tables together, indexing a long table, and for searching.</div>
Click OK when you've finished adding all the information to the New Table dialogue
box. Your Database Explorer should show you the new table you've just added:<br />
<br />
<div align="center">
<img alt="The Database Explorer showing the added table" height="184" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/database_explorer.gif" width="193" /></div>
Now that you've set up the table, you can start adding data to it. Click the
link below, Add data to your table.</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5674826708386228415.post-2999962619248991392014-03-12T12:17:00.003-07:002014-03-12T12:17:43.865-07:00SQL Server Express and C# .NET<div dir="ltr" style="text-align: left;" trbidi="on">
In this section, you’ll learn how to create a database with SQL Server Express.
You can do all this within the Visual C# .NET software. Once you have a database,
you’ll learn how to pull records from it, and display them on a Windows Form.
You will also learn how to navigate through the records in your database, and
how to add new records.<br />
<h3>
How to Create a SQL Server Express Database</h3>
Start a new project, and call it anything you like as we're only using this
project to create a database. But do remember where on your hard drive you saved
this project to, usually in your Documents folders, under Visual Studio, then
Projects. When a database is created, it will be saved in the project folder.
You’ll need to browse to this folder to add the database as resource when we
create a new project.<br />
From the menu at the top, click on Project > Add New Item.<br />
<div align="center">
<img alt="Add New Item" height="368" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/add_new_item.gif" width="379" /></div>
From the <b>Add New Item</b> dialogue box, look for the <b> Service-based database</b>
item, as in the image below:<br />
<div align="center">
<img alt="The Add New Item dialogue box" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/new_service_based2.gif" /></div>
In the Name box at the bottom, type Employees.mdf. Then click the <b>Add</b>
button.<br />
If you have Visual Studio Express 2013, you'll go straight back to your Form,
and it will look like nothing has happened. In version 2010 and 2012 of the
software, you'll see this screen:<br />
<br />
<div align="center">
<img alt="Wizard - Database Model" height="505" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/wizard_2.gif" width="661" /></div>
Select <b>Dataset</b>, then click <b>Next</b>. You'll then see this:<br />
<div align="center">
<img alt="Database objects screen" height="405" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/add_new_db_ds.gif" width="641" /></div>
Change the name of the Data Set to <b>ds_employees</b>.<br />
Click the Finish button to go back to your form. <br />
It might look as though nothing has happened, after you click the Finish button.
But have a look at the Solution Explorer at the top right of your screen. You
should see your database there:<br />
<br />
<div align="center">
<img alt="Solution Explorer showing a database added to a project" height="252" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/sql_server/solution_explorer_mdf.gif" width="312" /></div>
When you save your project, the database will get saved along with all the
solution files.<br />
In the next part, you'll learn how to add a table to the database.</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5674826708386228415.post-32553707316893442382014-03-12T12:17:00.001-07:002014-03-12T12:17:16.419-07:00How to Copy a File in C# .NET<div dir="ltr" style="text-align: left;" trbidi="on">
You can copy a file quite easily. It's done with the File class of System.IO.
Let's see how. First create a new folder on your C drive. Give it the name copiedFiles.<br />
Add a new button to your form. Double click to get at the code, and set up
the following files and directory paths:<br />
<div class="indent_small">
string fileToCopy = "C:\\test1.txt";<br />
string newLocation = "C:\\copiedFiles\\test1.txt";<br />
string folderLocation = "C:\\copiedFiles";</div>
In Windowscversions later than XP, you may have to change the file paths to
your Documents folder:<br />
<div class="indent_small">
string fileToCopy = "C:\\Users\\Owner\\Documents\\test1.txt"<br />
string newLocation = "C:\\Users\\Owner\\Documents\\copiedFiles\\test1.txt";<br />
string folderLocation = "C:\\Users\\Owner\\Documents\\copiedFiles; </div>
So the file we want to copy is <b>test1.txt</b> and it is in the root folder
of the C drive. We want to copy it to a new location. The folder (Directory)
we want to copy it to is called <b>copiedFiles</b>. We added a Folder Location,
because we want to check if this Directory exists.<br />
To copy a file, you use the Copy method of the File class:<br />
<div align="center">
<b>System.IO.<i>File</i>.Copy( fileToCopy, newLocation );</b></div>
In between the round brackets of Copy, you need a file to copy and the new
location of the file you're trying to copy.<br />
When the error checking is done as well, our code looks like this:<br />
<div align="center">
<img alt="C# code to copy a file" height="425" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2010/file_path_new7.gif" width="453" /></div>
The code checks to see if the Directory exists. If it does, then we check to
see if the file exist. If all is OK, then we go ahead and copy the file.<br />
Add the code to your own and try it out. When you click your button, you should
see the "File Copied" message box appear. If you look in the <b>copiedFiles</b>
folder that you created, you should see the <b>test1.txt</b> file there. <br />
<br />
<br />
<h3>
Move a File</h3>
To move a file to a new location, you would use the Move method of the File
class:<br />
<div align="center">
System.IO.File.<b>Move( </b>fileToMove, fileLocation <b>)</b>;</div>
Everything else is the same: type a file to move between the round brackets
of the <b>Move</b> method. Then, after a comma, add the new location.<br />
Don't forget to add your error checking as well!<br />
<br />
<h3>
Delete a File</h3>
To delete a file from your computer, you can use the <b>Delete</b> method of
the File class:<br />
<div align="center">
<b>System.IO.File.<i>Delete</i>( file_path );</b></div>
In between the round brackets of Delete, you need the name and path of the
file you are trying to get rid of. Be very careful when trying this one out
because it really does delete it. You won't find the file in the Recycle bin.<br />
<br />
<b>Conclusion</b><br />
File manipulation is a very useful skill for you to master as a programmer.
There's an awful lot more to it than in this book, obviously. But we've given
you more than enough power to be getting on with!<br />
In the next section, we'll take a look at databases and C#. The first thing
you'll learn how to do is to create a database with SQL Server Express. </div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5674826708386228415.post-48321531585662839932014-03-12T12:16:00.003-07:002014-03-12T12:16:38.892-07:00Write to a Text File in C# .NET<div dir="ltr" style="text-align: left;" trbidi="on">
To write to a text file, you use the <b>StreamWriter</b> instead of the StreamReader.
It's used in the same way, though:<br />
<div class="indent_big_no_bold">
System.IO.<b>StreamWriter</b> objWriter;<br />
objWriter = new System.IO.<b>StreamWriter</b>( file_name );</div>
Here, we're setting up a StreamWriter object and calling it <b>objWriter</b>.
When you create a new StreamWriter object, you hand it the name of a file between
the round brackets. Note that if the file is not found, no error will be raised.
This is because a file is created if one doesn't exist.<br />
Add another button to your form. Double click and type the following code for
it (If you have a Windows version later than XP you can add the longer <b>file_name</b>
lines, the ones with Environment.GetFolderPath, etc, from the <a href="http://www.homeandlearn.co.uk/csharp/csharp_s11p2.html">previous
section</a>):<br />
<div align="center">
<img alt="C# code to Write to a Text File" height="198" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2010/file_path_new5.gif" width="397" /></div>
Notice the line the does the writing:<br />
<div align="center">
<b>objWriter.Write( textBox1.Text );</b></div>
After the dot, use the Write method. In between the round brackets of Write,
add what it is you want to write to your file. For us, this was the Text in
textBox1.<br />
We also close the StreamWriter object, after we have finished with it.<br />
If you want to write line by line, instead of all at once, use this:<br />
<div align="center">
<b>objWriter.<i>WriteLine( )</i>;</b></div>
In between the round brackets of WriteLine, you add the line that you want
to write to your text file. This is normally done in a loop, and is useful if
you have an array of text that you want to write to a file. Here's a coding
example that does just that. See if you can work out what's happening. Try it
yourself.<br />
<div align="center">
<img alt="C# code to write to a text file line by line" height="427" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2010/file_path_new6.gif" width="487" /></div>
The for loop is where we write each line to the text file, adding a carriage
return and new line character. <br />
<br />
<h3>
Appending text to a file</h3>
When you use either Write or WriteLine, it will overwrite the current file.
So if you click your button twice, it won't add the new text to the end. It
will just erase whatever is already there, and write it again.<br />
If you want to add more text to what you already have, then you need to append.
This is quite easy, and is done with the StreamWriter line:<br />
<div align="center">
<b>objWriter = new System.IO.StreamWriter( file_name, <i>true</i>
);</b></div>
Between the round brackets of StreamWriter, and after the file you want to
use, you type <b>true</b> to append data to your file. The default is <b>false</b>.<br />
And that's it - no need for anything else!<br />
Coming up next - How to Copy a file with C#.</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5674826708386228415.post-66683683991827319642014-03-12T12:16:00.001-07:002014-03-12T12:16:11.495-07:00Read a file line by line in C# .NET<div dir="ltr" style="text-align: left;" trbidi="on">
Quite often, you'll want to read the contents of a text file line by line,
as part of some processing operation. You can then move on to the next line
and process that before moving on.<br />
To do that, you need the ReadLine method of the StreamReader object. But it's
not quite as straightforward as the ReadToEnd method.<br />
Along with the ReadLine method, you use the Peek method in a Do loop. It sounds
complicated, but examine this code:<br />
<div class="indent_small">
<i>do</i><br />
{</div>
<div class="indent_big">
textLine = objReader.ReadLine() + "\r\n";</div>
<div class="indent_small">
} <i>while</i> (objReader.Peek() != -1);</div>
Inside of the Do loop, we have this:<br />
<div align="center">
<b>textLine = objReader.ReadLine() + "\r\n";</b></div>
The <b>ReadLine</b> method grabs one line from your text file. It's in a loop
so that we can grab all the lines, one line at a time. We're just handing the
line to a string variable called text_line. (The "<b>\r\n</b>" at
the end add a carriage return and a new line.)<br />
The <b>while</b> part of the loop is this:<br />
<div align="center">
<b>while (objReader.<i>Peek()</i> != -1);</b></div>
The <b>Peek</b> method checks one character at a time. If it doesn't find a
character it will return a value of minus 1. In which case, we can end the loop.
As long as Peek returns a value other than minus one, we keep looping.<br />
Try it out for yourself. Add another button to your form. Double click it to
get at the coding window. Add the following code to your new button:<br />
<div align="center">
<img alt="C# code to read a text file line by line" height="296" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2010/file_path_new4.gif" width="430" /></div>
In versions of Windows later than XP you can have these two lines in place
of the <b>file_name</b> above:<br />
<div class="indent_small">
string fldr ="\\test1.txt";<br />
fldr = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + fldr;</div>
Inside the <b>Do</b> loop, you can write whatever code you need to process
the line of text. But all we're doing is building up the <b>txtLine</b> variable.
After the loop ends, we're placing it all in the text box.<br />
Before running your programme, though, add another few lines to your text file.<br />
In the next part, you'll see how to write to a text file.</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5674826708386228415.post-88857546179612510802014-03-12T12:15:00.003-07:002014-03-12T12:15:44.201-07:00Open a Text File in C# .NET<div dir="ltr" style="text-align: left;" trbidi="on">
As a programmer, you should have the ability to manipulate files. By this we
mean opening and processing things like text files, html files, word docs, etc.
In this section, you'll learn how to do that. First up is opening a text file.<br />
<h3>
<br />
How to open a Text File in C#</h3>
What we'll do is to open up a plain text file and insert the contents into
a text box. So start a new project. Add a text box and a button to your form.
Set the MultiLine property of the text box to true.<br />
Before you double click your button, you'll need to create a text file. Use
the Windows Notepad to create the following text file:<br />
<br />
<div align="center">
<img alt="Notepad with some text in it" height="259" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/textfiles/notepad.gif" width="360" /></div>
(The Windows Notepad can be found by clicking <b>Start > All Programs >
Accessories</b>, in both XP and Vista/Windows7.)<br />
Save it anywhere you like, but we recommend saving to your root drive if you
have XP. The file path would then be C:\test1.txt. For later versions of Windows,
save it to your Documents folder. The file path would then be:<br />
<div class="indent_big">
"C:\\Users\\Owner\\Documents\\test1.txt"</div>
But you can also use this rather long line:<br />
<div class="indent_small">
string fldr ="\\test1.txt";<br />
fldr = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + fldr;</div>
Once you have created and saved your text file, double click the button on
your form to get at the code. Add your file path as a string variable. Here's
the one for XP users:<br />
<br />
<div align="center">
<img alt="File path to text file - XP users" height="73" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2010/file_name_xp.gif" width="449" /></div>
And here's one for all other Windows users:<br />
<div align="center">
<img alt="Environment.SpecialFolder file path" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2012/chapter_textfiles/folder_path_code.gif" /></div>
Note that we have two backslash characters (\\) in the file name. This is because
if you just use one in C# it means "A special character follows".
The special character IS the backslash, so you need two: one to tell C# that
a special character follows, and one for the special character itself. This
is known as <b>escaping</b>.<br />
To open up text files, C# .NET uses something called the <b>StreamReader</b>.
This is an inbuilt class that lives in the <b>Input/Output</b> namespace. (A
namespace is a collection of related classes, all grouped together.) The Input/Output
namespace, or IO for short, lives in the System namespace. We need to set up
a <b>StreamReader</b> variable, so the code would be this:<br />
<div align="center">
<b>System.IO.StreamReader </b>objReader</div>
This sets up a StreamReader variable that we've called objReader. You then
create a new object with the name objReader:<br />
<div align="center">
<b>objReader = new System.IO.StreamReader( </b>file_name<b>
);</b></div>
After the new keywords, we have System.IO.StreamReader again. However, after
StreamReader we have a pair of round brackets. The file you want to open goes
between the round brackets. For us, this was held in the variable we called
file_name. Add the two lines to your code, and your coding window should look
like ours below (This is the XP <b>file_name</b> version just so that we can
have a smaller images):<br />
<div align="center">
<img alt="C# code for a StreamReader Object" height="121" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2010/file_path_new.gif" width="392" /></div>
Now that we have a StreamReader object, we can use its properties and methods.
To place the entire contents of a file in to a text box, you can use the ReadToEnd
method. As its name suggests, this reads all the contents of the file. Add this
line to your code:<br />
<div align="center">
textBox1.Text = objReader.<b>ReadToEnd()</b>;</div>
Once opened, a Streamreader should be closed. This is quite simple:<br />
<div align="center">
objReader.<b>Close()</b>;</div>
After adding the close line, your code should look like this:<br />
<div align="center">
<img alt="C# code to open a text file" height="180" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2010/file_path_new2.gif" width="401" /></div>
Run your programme and test it out. You should find that the contents of your
text file appear in your text box when your button is clicked.<br />
Stop your programme and return to your code. Change your file_name line to
this:<br />
<div align="center">
<b>string file_name = "C:\\test1111.txt";</b></div>
In other words, just add three more 1's to the file name. Run your programme
and click the button again. Unless you have a file called test1111.txt on your
C drive, you should see this error message appear (Visual Studio 2012/13 users
will see a plainer version of the error below):<br />
<div align="center">
<img alt="File Not Found Error" height="233" src="http://www.homeandlearn.co.uk/csharp/images/textFiles/fileNotFoundError_p119.gif" width="402" /></div>
You can test to see if a file exists. Again, you use the System.IO namespace.
But this time you use the File class. Here's the code:<br />
<div class="indent_small">
if ( System.IO.File.Exists( file_name ) = = true )<br />
{</div>
<div class="indent_big_no_bold">
//OPEN FILE HERE</div>
<div class="indent_small">
}<br />
else<br />
{</div>
<div class="indent_big_no_bold">
//ERROR MESSAGE HERE</div>
<div class="indent_small">
}</div>
So the line that checks to see if the file exists is this:<br />
<div align="center">
<b>System.IO.File.Exists( file_name ) == true</b></div>
<b>Exists</b> is a method available to <b>File</b>. Between the round brackets
of Exists, you type the name of the file you want to check. After a pair of
double equals signs, we're checking for a value of <b>true</b>.<br />
Place the code that opens the file between the curly brackets of the IF statement.
Add an error message for the <b>else</b> part, and we have this:<br />
<div align="center">
<img alt="C# code to check if the file exists" height="295" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2010/file_path_new3.gif" width="419" /></div>
So the file gets checked to see if it exits. If it doesn't, we display an error
message. If it does, the file is opened.<br />
You can also check to see if a folder (Directory) exists. Just use <b>Directory</b>
instead of <b>File</b>. Like this:<br />
<div class="indent_big">
if ( System.IO.Directory.Exists( folder_location ) )<br />
{</div>
<div class="indent_big">
}</div>
</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5674826708386228415.post-68336492084588347952014-03-12T12:15:00.001-07:002014-03-12T12:15:13.181-07:00Static Methods in C# .NET<div dir="ltr" style="text-align: left;" trbidi="on">
If all you want is an easy way to set up a few methods, and call them at will,
you can set up a class filled with public static methods.<br />
Static methods don't need an object. So you don't do this to create them:<br />
<div align="center">
<b>MyClass object_name = new MyClass( )</b></div>
Instead, you just call them when needed. Let's see how.<br />
From the C# menu bar at the top, click Project > Add Class. Call your new
class stats. Type the following code between the curly brackets of your new
class:<br />
<div class="indent_small">
public <i>static</i> int addUp(int num1, int num2)<br />
{</div>
<div class="indent_big">
return num1 + num2;</div>
<div class="indent_small">
}</div>
The only thing here that's different from a normal Method is the use of the
word <b>static</b>. Note that it comes after public but before int. You can
use any of the other variables types as well, such as <b>static string</b>,
or <b>static bool</b>, etc.<br />
Add a button to your form, and double click to get at the code.<br />
To use the static Method in your new class, the syntax is just this:<br />
<div align="center">
<b><i>class_name.method_name( )</i></b></div>
Because it's a static method, you don't have to go to the bother of setting
up a new object - your method will available straight away.<br />
Add the following code to you button to try it out:<br />
<div class="indent_big">
string answer;</div>
<div class="indent_big">
answer = <i>stats.addUp</i>( 5, 4 ).ToString();</div>
<div class="indent_big">
MessageBox.Show(answer);</div>
The class name <b>stats</b> will appear on the IntelliSense menu without you
having to do anything else. And when you type a dot after your class name, the
static method will appear on the list.<br />
There's an awful lot to static members, obviously. For example, you can create
static fields, static properties, and even static constructors. But if you want
a class filled with methods that you want quick access to, then just use static
methods.<br />
<br />
We'll leave classes now and move on. But if you want to get grips with C# .NET,
especially if you want a career as a programmer, then classes are something
you need to study.</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5674826708386228415.post-40871988044802929112014-03-12T12:14:00.001-07:002014-03-12T12:14:36.142-07:00Method Overloading in C# .NET<div dir="ltr" style="text-align: left;" trbidi="on">
Something else that you can do with classes is called Method Overloading. This
is when you want a slightly different version of a Method. It's part of another
Object Oriented concept called <b>Polymorphism</b>.<br />
<div align="left">
As an example, take the Method in our derived class. This one:</div>
<div align="center">
<img alt="A Method in the Class" border="1" height="176" src="http://www.homeandlearn.co.uk/csharp/images/classes/overloadCodeA.gif" width="356" /></div>
All this does is to return a string, depending on whether the <b>haveParty</b>
variable is true or false. But what if you wanted a different version of the
message, if you wanted to add the person's name as well, for example? That's
where Method Overloading comes in.<br />
The easiest way to do it is to simply copy and paste the Method you have. To
Overload it, you just add more parameters. Compare this version of the <b>getParty</b>
Method:<br />
<div align="center">
<img alt="A Second Class Method" border="1" height="173" src="http://www.homeandlearn.co.uk/csharp/images/classes/overloadCodeB.gif" width="419" /></div>
In between the round brackets of <b>getParty</b>, we've added a second parameter:<br />
<div align="center">
<b>string aName</b></div>
And in the Method body, the message that gets returned is slightly different.<br />
When we come to use our getParty Method from the button, look what happens:<br />
<br />
<div align="center">
<img alt="An Overloaded Method in C#" border="1" height="147" src="http://www.homeandlearn.co.uk/csharp/images/classes/overload.gif" width="483" /></div>
The Method is showing up on the IntelliSense list. The tool tip is telling
us that the Method has 1 overload.<br />
As soon as you type the first round bracket, the Method options, the overloads,
show up:<br />
<div align="center">
<img alt="First Overload Method" border="1" height="54" src="http://www.homeandlearn.co.uk/csharp/images/classes/overload2.gif" width="328" /></div>
In between the up and down arrows, it says 1 of 2. This means that there are
two version of the getParty method. Press the down arrow to see the second one:<br />
<div align="center">
<img alt="Second Overload Method" border="1" height="51" src="http://www.homeandlearn.co.uk/csharp/images/classes/overload3.gif" width="390" /><br />
</div>
The first version is our original, with one argument. The second version is
the new one, with two arguments.<br />
When you overload a method, it takes the same return type (public string, public
int, public float, etc). It's the parameters in between the round brackets that
change. In the second version of our method, the first parameter is a bool,
and the second parameter is a string. But you could have this instead:<br />
<div align="center">
<b>public string getParty( string aName )</b></div>
So we still have one parameters, but the type of variable is a string instead
of a bool. This is enough to set up a third overloaded method:<br />
<div align="center">
<img alt="A Third Overloaded Method" border="1" height="55" src="http://www.homeandlearn.co.uk/csharp/images/classes/overload4.gif" width="335" /></div>
We now have 2 of 3 between the up and down arrows - our new overloaded method
has been added to the list.<br />
Overloading can come in very handy if you want slight different versions of
a Method - just change the parameter list.<br />
Before we leave classes, we'll examine a simpler way to create classes. It's
not recommend that you create all your classes like this though! So, in the
final part of this section, we'll take a look at Static Methods. </div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5674826708386228415.post-72842745580915557522014-03-12T12:13:00.003-07:002014-03-12T12:13:53.759-07:00Inheritance in C# .NET<div dir="ltr" style="text-align: left;" trbidi="on">
Another important concept in Object Oriented programming is <b>Inheritance</b>.
It's easier to show you what inheritance is through programming examples, rather
than explain in words. But essentially inheritance is creating one class from
another. The parent class is the main one, and your create a child class that
does similar but slightly different things.<br />
Let's see if we can't make things clearer with a programming example.<br />
<br />
<div align="left">
Take a look at the new version of our Happy Birthday class. It's
been stripped down:</div>
<div align="center">
<img alt="C# Class Code" border="1" height="361" src="http://www.homeandlearn.co.uk/csharp/images/classes/inheritanceHB.gif" width="460" /></div>
We've deleted the properties, and now have just two public Methods. The default
constructor is still there, though. It just sets some default text for the two
variables.<br />
Inheritance is creating a child class from this parent. The parent is known
as the <b>base</b> class. The child class is known as a <b>derived</b> class.
The derived class can use all of the methods from its base class. But it will
have it's own code. Here's a class derived from the above Happy Birthday class:<br />
<div align="center">
<img alt="A Derived Class in C# .NET" border="1" height="430" src="http://www.homeandlearn.co.uk/csharp/images/classes/inheritance_Derived.gif" width="426" /></div>
What we want to do is to create another class called <b>BirthdayParty</b>.
Because the two are related, we can use Inheritance. This means that we don't
have to start all over again. We can just reuse the <b>HappyBirthday</b> class.
For example, suppose we wanted to display the following message:<br />
<div align="center">
<b>Happy Birthday Shahid!<br />
You have 8 Presents<br />
Enjoy your Party!</b></div>
We can get the first two message from the base class (<b>HappyBirthday</b>).
But we can get the final message from the new class, <b>BirthdayParty</b>. Birthdays
and parties are closely related. But we want to keep one separate from the other.
We could then add more information about the party: number of guests, location,
time, etc. But we'd add this to the derived class, instead of the base class.<br />
Note the first line from the derived class:<br />
<div align="center">
<b>class BirthdayParty : HappyBirthday</b></div>
You start by typing the word <b>class</b>, followed by a space. You then need
to come up with a name from your new class. We called ours BirthdayParty. Because
we want to use some of the code from the base class, we have this:<br />
<div align="center">
<b>: </b>HappyBirthday<br />
</div>
So to specify that this is a derived class, you type a colon ( : ). After the
colon, you type the name of the base class.<br />
The only other thing that's different is this:<br />
<div class="indent_big">
public BirthdayParty() :base()<br />
{</div>
<div class="indent_big">
}</div>
We're setting up a default constructor called BirthdayParty, the same name
as the new class. This is where you can set up variables for this particular
class. But this constructor knows nothing about the code from its parent class,
HappyBirthday. To tell it to run the code for the parent constructor as well,
we have this:<br />
<div align="center">
<b>:base( )</b></div>
When the programme runs, C# will initialise variables for the new derived class
as well as the variables in the base class.<br />
Here's some code that uses both classes. This is from a button on a form:<br />
<div align="center">
<img border="1" height="154" src="http://www.homeandlearn.co.uk/csharp/images/classes/inheritanceButtonB.gif" width="402" /></div>
We've created a new <b>BirthdayParty</b> object and called it <b>partyOn</b>.
Then comes three message boxes. The first two call the Methods from the <b>HappyBirthday</b>
class. The final one calls the Method from the derived class, which is <b>BirthdayParty</b>.<br />
Study the code and see how it works. Create a new project and try it out. <br />
Inheritance can get very tricky, and it's difficult to know what to put in
to the base class and what to put in the derived class. But it's usual to create
a base class that holds general information, and a derived class that contains
more information. For example, you might have an automobile class as the base
class. A car class and a motorbike class could then be derived from automobile.
<br />
In the next lesson, we'll take a look at Method Overloading.</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5674826708386228415.post-71472403480000116932014-03-12T12:13:00.001-07:002014-03-12T12:13:13.752-07:00Class Constructors in C# .NET<div dir="ltr" style="text-align: left;" trbidi="on">
Quite often, you'll want to set some default values for the variables you've
set up in your class. This is where the Class Constructor comes in handy.<br />
Suppose we want to add a new property to our class, the number of presents
a person receives on their birthday. We can set up a new variable in our HappyBirthday
class:<br />
<div align="center">
<b>private int numberOfPresents;</b></div>
This integer variable (a field) has no value at the moment. We can use a Constructor
to set one.<br />
<div align="left">
A Constructor is used to set up values for your variables. When
your object is created, C# looks for this Constructor and tries to set those
values. If you don't add one yourself, C# automatically adds one for you. Even
if you have no variables to set!</div>
The Constructor takes the same name as your class. For us, the default Constructor
will be called <b>HappyBirthday</b>, and would look like this:<br />
<div class="indent_big">
public HappyBirthday()<br />
{</div>
<div class="indent_big">
}</div>
Note that Constructor is <b>public</b>, but that it has no return type like
int, string, float, etc. That's because Constructors don't return values - they
just get on with setting up values for your variables.<br />
A default Constructor has nothing between the round brackets after its name.
If you set up your own default Constructor, rather than letting C# do it for
you, then leave the round brackets empty. (You can also do something called
Constructor Overloading, but that's outside the scope of this book. But this
is where you pass values over to your Constructor.)<br />
To set a value for our <b>numberOfPresents</b> variable, we just do normal
variable assignment:<br />
<div class="indent_small">
public HappyBirthday()<br />
{</div>
<div class="indent_big">
numberOfPresents = 0;</div>
<div class="indent_small">
}</div>
Now, when the object is created, C# will fill our <b>numberOfPresents</b> variable
with a default value we have chosen.<br />
Let's put the numberOfPresents variable to some use.<br />
Add the following property to your class:<br />
<div class="indent_small">
public int PresentCount<br />
{</div>
<div class="indent_big">
set { numberOfPresents = value; }</div>
<div class="indent_small">
}</div>
The property is write-only, meaning we are only setting a value, not getting
one out. But it will set a value for the numberOfPresents variable.<br />
Your getMessage Method can be amended slightly, too. Change it to this:<br />
<div class="indent_small">
private string getMessage(string givenName) {</div>
<div class="indent_big">
string theMessage;</div>
<div class="indent_big">
theMessage = "Happy Birthday " + givenName + "\n";<br />
theMessage += "Number of presents = " + numberOfPresents.ToString();</div>
<div class="indent_big">
return theMessage;</div>
<div class="indent_small">
}</div>
All we're doing is setting up a string variable called theMessage. We're then
building up the string with the givenName and the numberOfPresents. Note the
use of the C# new line character, "\n".<br />
In your button code, you can now set a value for your new property:<br />
<div align="center">
<b>birthdayMessage.PresentCount = 5;</b></div>
The coding window for your button should then look like this:<br />
<div align="center">
<img alt="Set a value for the property" border="1" height="188" src="http://www.homeandlearn.co.uk/csharp/images/classes/presentProperty_p107.gif" width="415" /></div>
The new property use has been highlighted. We're passing a value of 5 over
to the PresentCount property we set up.<br />
Here's what your HappyBirthday class should look like. We've added a few comments.<br />
<div align="center">
<img alt="The C# HappyBithday Class code" border="1" height="750" src="http://www.homeandlearn.co.uk/csharp/images/classes/classHappyBirthday_p108.gif" width="514" /></div>
Run your programme and click your button. The message that displays should
look like this:<br />
<div align="center">
<img alt="Message Box" height="169" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/classes/message_box_shahid2.gif" width="189" /></div>
<br />
<b>Exercise O</b><br />
Set up a new property to record whether a person is having a birthday party
or not. Add a default value of false to your constructor. Adapt your message
accordingly. When you use your new property from the button code, pass over
a value of true. <br />
If you successfully complete this exercise, your message box may look something
like this if they are having a party:<br />
<div align="center">
<img alt="Message Box Two" height="184" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/classes/message_box_shahid3.gif" width="203" /></div>
And like this if they are not:<br />
<div align="center">
<img alt="Message Box Three" height="184" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/classes/message_box_shahid4.gif" width="189" /></div>
To get different messages, you will have to add an if statement to your Method.
<br />
This is a tricky exercise. So give yourself a pat on the back, if you complete
it!</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5674826708386228415.post-92114906966418537692014-03-12T12:06:00.003-07:002014-03-12T12:06:44.169-07:00Using your Properties in C# .NET<div dir="ltr" style="text-align: left;" trbidi="on">
Now that you've set up a property in your class, you can put it to use. First,
comment out any code for your first button. Place a new button on your form.
Double click the button to get at the code. <br />
The first thing to do is to create an object from your class:<br />
<div align="center">
<img alt="A new Object created from a Class" border="1" height="94" src="http://www.homeandlearn.co.uk/csharp/images/classes/propertyUse_p102.gif" width="404" /></div>
In the above code, we've created a HappyBirthday object and called it birthdayMessage.<br />
To pass something over to your new property, you use dot notation. So type
birthdayMessage followed <br />
<div align="center">
<img alt="The Property appears on the IntelliSense List" border="1" height="132" src="http://www.homeandlearn.co.uk/csharp/images/classes/propertyUse2_p102.gif" width="394" /></div>
<div align="left">
And there's the property you set up! The name of the property
is <b>MyProperty</b>. That, however, is the default name. You can call your
properties almost anything you like, just as you can with variables.</div>
Double click your property to add it to your code.<br />
To pass something in, you need an equals sign, followed by the information
you want to pass to your property:<br />
<div align="center">
birthdayMessage.<b>MyProperty</b> = "Shahid";</div>
In the code above, we're passing the text "Shahid" to our property.
<br />
To get something back out from your property, the syntax is this:<br />
<div align="center">
<b><i>your_data = object_variable_name.property_name;</i></b></div>
After the equals sign, you need the name of your object. Then type a dot. The
IntelliSense list should appear again. Select your property from the list. End
the line with the usual semicolon.<br />
So add the following lines to your code:<br />
<div align="center">
<img border="1" height="184" src="http://www.homeandlearn.co.uk/csharp/images/classes/propertyUse3_p102.gif" width="408" /></div>
Note the two lines that use the property:<br />
<div class="indent_big">
birthdayMessage.MyProperty = "Shahid";<br />
returnedMessage = birthdayMessage.MyProperty;</div>
The first one is setting a value for the property. The second line is getting
something back out. We're then handing it over to a string variable called returnedMessage.
This can then be displayed in a message box.<br />
If you're not sure quite what's going in, study the following images:<br />
<br />
<div align="center">
<img alt="How C# Properties work" height="491" src="http://www.homeandlearn.co.uk/csharp/images/classes/propertyUse4C_p102.gif" width="432" /></div>
The image shows that the text "Shahid" from the button is getting
handed over to the <b>value</b> variable in the <b>set</b> part of the property.
The getMessage( ) method can then do something with this value. After it constructs
the message, it hands it over to the <b>birthdayMessage</b> variable. The <b>get</b>
part of the property can then see what's inside of the birthdayMessage variable.<br />
Here's a pair of images showing what is happening when we get the value out
of the property:<br />
<div align="center">
<img alt="Getting the value of a Property" height="491" src="http://www.homeandlearn.co.uk/csharp/images/classes/propertyUse4D_p102.gif" width="432" /></div>
So the value in the class variable birthdayMessage is getting handed over to
MyProperty in the button code. Once we get the value from the property, it is
handed over to the returnedMessage variable.<br />
In the next lesson, you'll learn about Class Constructors.</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5674826708386228415.post-79985000126985289542014-03-12T12:06:00.001-07:002014-03-12T12:06:05.253-07:00Adding Properties to your C# Classes<div dir="ltr" style="text-align: left;" trbidi="on">
You've been using properties a lot throughout this book: setting the Text property
for a Textbox, setting size properties, setting font properties, etc. The way
you did it in code was this:<br />
<div align="center">
textBox1.<b>Text</b> = "My Text";</div>
So the object is called textBox1. This textBox1 object has a property called
<b>Text</b>. To set a value for the Text property, you're typing a string between
double quotes, and after an equals sign ( = ).<br />
Behind the scenes, this property value gets handed over to a class, so that
something can be done with it.<br />
C# .NET allows you to set up your own properties, so that they can be used
the same way. Let's see how it's done.<br />
The only thing you have in your class at the moment is a private method:<br />
<div class="indent_small">
private string getMessage(string givenName)<br />
{</div>
<div class="indent_big">
return "Happy Birthday " + givenName;</div>
<div class="indent_small">
}</div>
This Method can't be seen from the outside world. But that doesn't mean that
it can't be used inside of the class. We'll have our property call this method.<br />
But our property will do the following:<br />
<ul>
<li>Allow us to pass a value over to our class</li>
<li>Allow us to get that value back out of the class</li>
</ul>
The easy way to add a property to your class is via the Insert Snippet menu.
So right click just after the final curly bracket of your getMessage Method.
You should see the following menu appear:<br />
<div align="center">
<img alt="The Insert Snippet menu" border="1" height="357" src="http://www.homeandlearn.co.uk/csharp/images/classes/insertSnippet_p100.gif" width="307" /></div>
Select Insert Snippet to see the following (Visual Studio 2012 users will see
another menu first, with C# on it. Double click C# to see the menu below):<br />
<div align="center">
<img alt="The list of C# Snippets" height="117" src="http://www.homeandlearn.co.uk/csharp/images/classes/insertSnippetProp_p100.gif" width="102" /></div>
Select <b>prop</b> from the list and C# will add this default code (Visual
Studio 2012 users should select <b>propfull</b> from the menu instead of <b>prop</b>):<br />
<div align="center">
<img alt="The default snippet code for a C# Property" border="1" height="120" src="http://www.homeandlearn.co.uk/csharp/images/classes/insertSnippetProp2_p100.gif" width="195" /></div>
The code is a little bit baffling, so we'll go through what's been added.<br />
The default code is for an integer property called <b>MyProperty</b>. A private
integer variable has also been set up. (Variables inside of your own classes
are called <b>Fields</b>.)<br />
But we want to return a birthday message as a string, not as an integer. So
change your property to this:<br />
<div align="center">
<img alt="Get and Set for C# Properties" border="1" height="119" src="http://www.homeandlearn.co.uk/csharp/images/classes/insertSnippetProp3_p100.gif" width="268" /></div>
So the name of the variable outside of the property has been changed to birthdayMessage:<br />
<div align="center">
<b>private string birthdayMessage;</b></div>
This means that the variable will now be visible from everywhere in the class.<br />
Note that we've also replaced myVar with birthdayMessage inside of the property.<br />
The structure of the property is this:<br />
<div class="indent_big">
public string MyProperty<br />
{</div>
<div class="indent_big">
}</div>
This sets a property called <b>MyProperty</b>. You can change this to almost
anything you like - it's just the same as a variable name.<br />
Inside of the property body, you have an area that gets values out:<br />
<div align="center">
<b>get { return birthdayMessage; }</b></div>
And an area where you can put values in (<b>set</b> them):<br />
<div align="center">
<b>set { birthdayMessage = value; }</b></div>
The keywords <b>get</b> and <b>set</b> are used for this purpose. The value
is the value you will be passing in to the property. Change the line to this:<br />
<div align="center">
birthdayMessage = <b>getMessage( </b><i>value</i><b> );</b></div>
We are now using our private <b>getMessage</b> Method. The <b>value</b> being
handed over to our Method will be the value that gets handed over to the property.<br />
(If you only need to hand values over and not get them out, then just use the
<b>set</b> part. This is known as a write-only property. If you just want to
get values out, then just use the <b>get</b> part. The property will then be
read-only.)</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5674826708386228415.post-86726574564666257282014-03-12T12:05:00.001-07:002014-03-12T12:05:13.541-07:00Passing values to your C# Classes<div dir="ltr" style="text-align: left;" trbidi="on">
The message that displays in <a href="http://www.homeandlearn.co.uk/csharp/csharp_s10p3.html">the previous lesson</a>
is just "Happy Birthday". But what if you wanted the name of a person
as well, "Happy Birthday, Shahid!"? What you need is a way to pass
information over to your classes.<br />
There are several ways to pass data to your classes. An easy way is to simply
pass the information as an argument, between the round brackets of the method.
<br />
Change the Method in your class to this (the new additions are in bold):<br />
<div class="indent_small_no_bold">
public string getMessage(<b>string givenName</b>)<br />
{</div>
<div class="indent_big_no_bold">
return "Happy Birthday " + <b>givenName</b>;</div>
<div class="indent_small_no_bold">
}</div>
So we've just added a string variable called <b>givenName</b> between the round
brackets of the Method. We then use this in the code.<br />
If you try to start your programme, however, you'll get an error message. C#
will underline this part of your code:<br />
<div align="center">
<b>birthdayMessage.getMessage( )</b></div>
Because you've added an argument to your method, you need some data between
the round brackets. Change the line to this:<br />
<div align="center">
<b>birthdayMessage.getMessage( "Shahid" )</b></div>
Run your programme again, and you should find that the following message displays:<br />
<br />
<div align="center">
<img alt="A Message Box in Visual C# .NET" height="154" src="http://www.homeandlearn.co.uk/csharp/images/csharp_2013/classes/message_box_shahid.gif" width="188" /></div>
So you're just passing data to your Method in the normal way.<br />
However, we set the method up to be public:<br />
<div align="center">
<b>public</b> string getMessage(string givenName)</div>
This is not the recommended way to pass information over to your classes, though.
Method are usually hidden from the outside world by making them private. This
"hiding" methods and variables in your class is known as Encapsulation.
The idea is that you hide as much of your class as possible. That way, it can't
be broken by passing information over that the class can't handle. A broken
class may crash your programme!<br />
So change the first line of your Method to this:<br />
<div align="center">
<b>private</b> string getMessage(string givenName)</div>
Try to run your programme and you'll get an error:<br />
<div align="center">
<b>"getMessage is inaccessible due to its protection level."</b></div>
The reason it's inaccessible is because you've made it private. So it can't
be see from outside of its own class. If that's the case, then how can you pass
values over? The answer is to set up a property instead. We'll do that in the
next lesson.</div>
Unknownnoreply@blogger.com0