Mapa mental
Part C 60%

Conteúdo do mapa
Part C 60%
Databases
- ‘Master detail’ relationships
- Q&A
- ‘Master detail’ relationships
Strings
- Strings and backslashes
- C# uses the backslash character in a string to mark out special characters.
- eg “\r\n” = used to create a pair of characters for return and newline that give an end of line mark. If we want to show three lines in a label we could use: Label1.Text = “111” + “\r\n” + “222” + “\r\n” + “333”;
- @-quoted string literals
- However this way of using backslashes causes problems if we want to store a Windows filename in a string. The C# way around this is to put a @ character before the first double quote of the string. This tells the compiler that in this string backslash characters are just treated as backslashes. So to hold the address of the C:\Temp folder in a C# string we would use; String tempFolder = @“C:\Temp”;
- String/numeric conversion
- Any numbers displayed or typed on the screen are actually stored as text characters. So to enter numbers, calculate and display the results we need to do a conversion both before and after the calculation.
- Enter a number on screen as text ð convert the input to a number ð do any calculations ð convert the results from numbers to text ð display the text results on screen
- text to numbers
- To do this you need to use one of the methods of the Convert class:
- truncate
- If we have numbers that contain a decimal part we may want to truncate them or round them to the nearest integer.
- To do this we use the methods from the Decimal class which is a class for holding a number with a fixed decimal point position. Since most of the numbers we are likely to round will be stored in one of the floating point types like double the code first shows a conversion from double to Decimal. We then use the Round and Truncate methods of the Decimal class. These methods return a Decimal value so we cast the results to int.
- numbers to text
- all numeric types have a .ToString() method that will return a string version of the number. However you can control the way that the number will display as text. The ToString() method for numeric types can have a formatting string passed to it as a parameter
- formatting string
- In this formatting string # is a placeholder for either a blank or a number 0 is a placeholder for either a zero or a number
- So if we have a formatting string “#00.0000” = show a number with at least two places before the decimal point and at least four places after the decimal point filling the spaces with zeros if necessary. With this formatting 1.23 would display as 01.2300
- Format() method
- This gives a way of putting a list of data into a string. The first argument of the Format() method takes the text you want to display with a list of place holders starting from {0} included in the text. The next arguments for the Format() method are a list of variables whose values you want to appear in the final text.
- Changing the case of a string
- C# has methods for changing the case of a string to all uppercase or all lowercase:
- Alter a string
- You cannot change a string once it has had some characters placed in it. The memory used to hold characters for a string is treated like a read only array. So in the following code str[1] gets the second character in the array ‘F’, ‘r’, ’e’, ’d’ and if we want to display this character we need to use the ToSting() method. However the the forth line will cause a compiler error saying that str[1] is read only.
- ToSting()
- The memory used to hold characters for a string is treated like a read only array. So in the following code str[1] gets the second character in the array ‘F’, ‘r’, ’e’,’d’ and if we want to display this character we need to use the ToSting() method. However the the forth line will cause a compiler error saying that str[1] is read only.
- appears to change
- However you can write code that appears to change a string.
- What C# is doing here is allocating more space for a new string and copying the characters from the old string and for “ and Joe” to the new area. It then uses the reference str to point to the new memory and the garbage collector will clean up the old memory later.
- StringBuilder class
- This does not matter if only a few characters or copies are involved. However all the extra copying can make a program noticeably slow if there are large numbers of characters or large numbers of copying operations.
- One way to avoid the need to keep finding new areas of memory and copying the characters from previous areas = to allocate enough space for the eventual string at the start. To do this we use the StringBulder class.
- Multiline textboxes
- By default a textbox control only allows one line of text.
- However if you change the .Multiline property to true = you can drag the sides of a textbox to give space for multiple lines of text. The lines of text in a multiline textbox are stored in its .Lines property as an array of strings.
- The user can alter the contents of any textbox, but a programmer cannot directly change the contents of the individual lines in .Lines You can get the value of one of the strings in .Lines by using array notation, textBox3.Text = textBox2.Lines[3]; However you cannot do the reverse and change the value of a line, the next statement gives a compiler error. textBox2.Lines[3] =textBox3.Text;
- Manipulating strings
- This covers a number of methods that let you work with substrings. The key methods are 1. finding the position of a substring in a larger string, 2. extracting a substring of a given length starting at a given position, 3. deleting a substring, 4 inserting a substring, 5 splitting a string into smaller parts based on a separator character and joining several strings to make a larger string with separator characters between each part.
- Finding the position of a sub string
- Extracting a substring from a larger string
- Deleting a sub string from a larger string
- Storing data in comma separated text files
- One useful way of storing data is to use a text file where each line represents a record and the fields in the record are separated by some special character – usually a comma.
- So the information: Name: Joe age:23 height: 1.8 Name: Sue age:31 height:1.6 Could be stored as two lines of text like this: Joe,23,1.8 Sue,31,1.6
- Strings and backslashes
Dates & Times Class
- C# provides a DateTime class that can be used to create objects for storing dates and or times. The DateTime class also provides a number of useful methods for working with dates and times.
- static methods
- can be used without needing a reference to an object, they are called by using the class name.
- Compare()
- IsLeapYear()
- IsLeapYear() method returns a true or false value saying whether a year is a leap year and is called with code like: DateTime.IsLeapYear(2007);
- DaysInMonth().
- DayOfyear() method
- DateTime Parse()
- Non static methods
- need to be called using a reference to a DateTime object.
- .ToShortTimeString()
- static properties
- .Now
- .Today
- Static methods and properties are used where a useful result can be obtained without needing to identify a specific object belonging to the class.
- DayOfWeek
- DateTimePicker
- Exception
Collections
- Arrays
- Arrays can be declared and initialized at the same time or initialized later. They can also be declared without stating how many items are stored in each dimension provided this is set before the array is used. Arrays cannot be extended beyond the initial sizes that you set
- We can declare an array to hold object references that point to Person objects:
- Project ArrayExamples
- Initializing an array
- Arrays of object references
- declare an array
- We can declare an array to hold object references that point to Person objects:
- array to hold object references
- We can then create up to 5 Person objects and use the People array to hold object references that point to these objects:
- Looping through an array or any collection
- The typical way of doing this is to use the foreach loop.
- declare an array
- Arrays of object references
- ArrayLists
- ArrayLists are a special type of class for holding collections of object references that can be extended to hold as many object references as needed. Usually an ArrayList will hold object references of the same type.
- ArrayLists are used to hold as many members as we need ArrayLists are a way of creating an expandable list ofsimple values or object references. This has an advantage over arrays as with an array we have to specify the maximum number of elements in advance. With anArrayList we can add as many elements as we wish.
- declaration of an ArrayList
- stores random integers
- code stores random integers in an ArrayList each time the button is clicked:
- Convert Value
- An ArrayList that contains only one type of value or object can be converted to an array of that type.
- In the next bit of code we convert the values in the NumbersList to an array of integers. We do this because we can work with the individual members in an array which cannot be done with an ArrayList.
- ToArray method
- ArrayLists are normally used to hold object references of a single class or descendants of a class. The reason for this is that when we want to deal with the elements in an ArrayList the easy thing to do is to convert them into an array. The ToArray method creates an array with enoughplaces to hold the current number of elements in the ArrayList.
- Note the use of casting to Person and the use of the typeof operator as we tell the ArrayList that the array we want to create is of type Person. [the highlighed code]
- Using an ArrayList as if it was an array
- However we can also use an array list with array notation using square brackets. The point to note here is that the references we get from the ArrayList are of type object so we need to cast them to the right type when we use them. Here is an alternative to the foreach loop in the code above where instead of converting to an array of Person object references we cast each object in the arrayList to a Person object as we come to it.
- The ArrayList class comes with a number of useful methods and properties for dealing with the object references it stores including Count, FindAt(), Clear(), Insert() and Delete()
- explain
- stores random integers
- ListBoxes
- Listboxes are a way of holding a collection of object references and making the members of the collection visible on the screen.
- Listboxes are visible collections A listbox holds a collection of references to objects or a collection of strings and makes a string visible for each member in the listbox. Listboxes have a SelectedIndexChanged event that will run code if the user clicks on a new line in the listbox.
- ToString() method
- One of the useful things about listboxes in C# is that when we use them to store references to objects we can get the string that shows in the listbox from the object itself. For this to work the object needs to come from a class that has an overloaded version of the ToString() method. For example in the Person class there is a ToString() method as follows.
- .Items property
- So if we have a Person object for a person called Fred aged 28 the ToString() method for that person will return “Fred (28)”. If we add a reference to this object to a listbox then the listbox will show a new line with this string.
- The next bit of code adds a reference to a new Person object to a listbox each time the button is clicked. For each new reference to a Person object that we add the listbox will display a string returned by using the object’s ToString() method. Note that the collection of object references stored in the listbox is held in the .Items property of the listbox.
- .SelectedItem property
- We can use the objects that are referred to by a listbox. In the next bit of code we get the object using the .SelectedItem property.
- This gives a reference to the object matching the line the user has clicked on. However the listbox does not know what type of object it is so before we can use it we need to cast it to a Person object. Then we can ask the object to run methods belonging to the Person class such as Show().
- Random Number
- C# provides the Random class that we can use to create random number generator objects.
- int num; Random rndm = new Random(); num = rndm.Next(26); //num will be between 0 and 25
- Arrays
Exception handling
- An exception is a situation that your program cannot cope with while it is running the code.
- For example you might have code that gets a number from a textbox: int n1 = Convert.ToInt32(textBox1.Text); If textBox1 contains “12AA” then the Conver.ToInt32() method will fail. What normally happens at this point is that your program crashes.
- exception handling routine
- There is a way to write code that will respond to exceptions by jumping to an exception handling routine instead of crashing. Here is a very simple example.
- What is happening here is that we put the code that may cause an exception inside what is called a try block. If there is no exception we just do the code in the try block. If an exception does happen, the C# runtime will store information about the exception in an Exception object and make ex in the Catch block refer to that exception object. The program will jump from the statement that caused the exception to the catch statement and then show the message box. Then the runtime will exit from thebtnProtected_Click event handler without crashing the program.
- General form
- The general form of C# exception handling is a try block followed by one or more catch blocks and optionally followed by a finally block.
- 2 sources of exceptions
- FormatException = textbox we get our number from contains some alphabetic characters.
- DivideByZeroException = condition is where we try to divide by zero and the result is integer infinity which C# cannot cope with.
- Exception ex
- There are lists of exception types available on the web and in the Software Development Kit (SDK) that is Microsoft’s knowledgebase for developers. You can find the exception types by starting with a general catch block that is set to catch any type of exception and then get the type from the error message.
- It is usually a good idea to put this sort of general purpose catch block at the end of all your other catch blocks, just before the finally block if there is one, so that if there is an exception you have not thought of it will still be caught. Note that you cannot put a general purpose catch block above more specific catch blocks, the compiler will object.
- Finally Block
- Sometimes there will be things that should be done at the end of a method whether or not there was an exception. A simple example might be turning an hourglass cursor back to the normal default cursor. More important examples would be disposing of resources such as Graphics objects or StreamReader objects that are the programmer’s responsibility to dispose of once they are finished with
- In cases like these we can use the finally block. This goes after the catch blocks and has the effect that code inside the finally block is always executed, whether there is an exception or not. In the code below if you leave off the finally block you will have a cursor that stays as an hourglass if there is any exception. With the finally block the cursor will always return to the normal cursor.
Drag and drop
- Drag and drop starts with the mouse button going down while the mouse is over the control that the drag starts from, this is called the drag source.
- The mouse button is then held down while the mouse is moved to a different control that is the target. During this stage the mouse cursor shows a no-drop icon, a crossed circle. This then changes to a cursor that indicates dropping is allowed when the mouse cursor enters the space over the target control.
- To make Drag Drop work in C# you need to carry out these steps: 1. Write code for the MouseDown event handler of the control where the drag starts. 2. Write code for the DragEnter event handler of the target control that will change the AllowDrop property of the target control to true. 3. Write code for the DragDrop event of the target control. 4. Add code to carry out any work needed after the drop has happened.
- MouseDown event handler
- In the MouseDown code we need to find which label had the MouseDown event so we cast the sender as a label and find its BackColor. We store the BackColor in a global variable: Label aLabel = sender as Label;dropColor = aLabel.BackColor;
- DoDragDrop() method
- We then call the DoDragDrop() method and store the result returned by this method in a structure of type DragDropEffects: DragDropEffects result = aLabel.DoDragDrop(0, DragDropEffects.All);
- DragEnter
- The DoDragDrop() method does not return its result immediately, instead it waits for a MouseUp event to say that the drag operation is finished.
- While the DoDragDrop() method is waiting the mouse moves away from the labels on the left and over the big light blue panel in the middle. So while the first event handler is still running, but is paused waiting for a MouseUp, the mouse moves into the space over the big light blue panel and triggers another event, the DragEnter event for the panel.
- DragDropEffects.All.
- The job done by the DragEnter event handler is to tell the application that dropping is allowed over the panel. What the user sees is that the cursor changes to a Drop cursor. You can actually set different types of Drop operations allowing Copy or Move actions but it is simplest to simply allow any type of drop which is what we do here by setting the Effect to DragDropEffects.All. Remember that the first event handler is still active while this is happening.
- DragDrop
- The next event handler to get involved in the Drag Drop process is the DragDrop event which happens when the user releases the mouse button over the panel.
- In the event handler for this event we do the work that carries out the effects we want from the drop.
- In the code below what we want is to change the color of the panel to match the color of the label where we started the drag. We made this easy since we stored the color in a global variable when the drag began. And yes, the MouseDown event handler of that label is still active.
- DoDragDrop()
- As part of dropping the mouse fires a MouseUp event as the button is released. This in turn leads to the DoDragDrop() method finally completing and returning a value into the result structure. So we are now back where we started, executing the next statement in the MouseDown event handler, which is the ‘if’ statement.
- If the result is equal to DragDropEffects.None this means that the mouse button was let go when the mouse was not over the panel, in effect the drag was abandoned. If result is not equal to DragDropEffects.None then the drop was over the panel and was successful so we can display “Drag completed”
- Drag Drop and Draw
- The DragDrop code here is very similar. There are two minor differences, we draw a colored ellipse when we drag from a label to the panel in the middle and when the drag is completed we update a count saying how many drags have taken place.
- Choose and use color
- The significant difference is how we hold the data for the color that we chose at the start of a drag and will use when a drop happens.
- MouseDown
- DoDrag()
- The first argument of the DoDrag() method is of type object and this means we can hold a reference to any object in this argument of the DoDrag() method.
- DragDrop event
- When it comes to the DragDrop event handler we need to use some horrible syntax to allow us to treat the object as a Color object:
- The DragDrop event handler’s second argument e contains a way of getting the object we sent as an argument to the DoDragDrop method.
- The core is e.Data.GetData but we need to proceed this with a cast to Color and we need to give it an argument giving the type of the data, in this case the type of a Color object.
- In order to do this we first create a dummy Color object so that in the next line we can use its getType() method: Color dummyColor = Color.Red; Color drawColor =(Color)e.Data.GetData(dummyColor.GetType());
- DoDrag()
- 3rd Tab
- Basically similar code to page 2 but it will be explained in more detail. The code to handle the steps 2, 3 and 4 described above are shown below for a an example of dragging items between two list boxes listBox1 and listBox2.
- The third tab on the form has a pair of radio buttons on it rbCopy and rbMove and if the rbCopy radio button is checked an item dragged from one listbox is added to the other listbox when it is dropped but the original item is left in the listbox it was dragged from. If the rbMove radio button is checked an item dragged from one listbox is added to the other listbox when it is dropped and then the original item is removed from the listbox that it was dragged from. This example is on the third tab of the tabbed page in the main form in the DragDrop1 project. Both listboxes need to have their .AllowDrop property set to true.
- MouseDown method of the source control
- In this code we are writing an event handler that can be used by either listbox when it has a mouse down event. After the code is written use the properties window and the events tab to make the MouseDown event of each listbox point to this code:
- The first job we do is get a reference to the actual listbox that had the MouseDown event. This is done in the line ListBox box = ((ListBox)sender);
- box.Items.SelectedItem
- Normally you would expect to be able to use box.Items.SelectedItem to get the item that was clicked in the listbox. However some bug in C# in the 2003 version means that this only works for the first item selected and does not recognize if a new item is selected. Therefore we use the IndexFromPoint(e.X,e.Y) method to find the index of the item that was clicked on.
- We then call the DoDragDrop() method. This tells Windows a drag operation is starting and the method will return a result indicating what happened when the drop was completed. This need to return a result giving information about the drop means that this method will not complete execution until the drop happens so the next line will not be completed until after the drop: DragDropEffects result = box.DoDragDrop(box.Items[index],DragDropEffects.All);
- The final lines of this method will remove the dropped item from the listbox it came from provided the rbMove radio button is checked. if ((rbMove.Checked) && (result != DragDropEffects.None) ) { box.Items.RemoveAt(index); }
- There is a further condition in the if statement (result != DragDropEffects.None) What we are checking here is that the drop did not happen over the form. If the drop had happened over the form we would regard the drop as abandoned or cancelled and the value that this returns from the DoDragDrop() method is DragDropEffects.None.
- DragEnter event of the target control
- Again since both list boxes can serve as targets of a drop make the DragEnter events of both listboxes point to the following code. The code here is simple. We will check to see that there is text in the item to be dropped and if so change the drag cursor to indicate that dropping is allowed.
- Revision
- We could write a version that sets the drag cursor to a Move cursor or a Copy cursor depending on the radio buttons, but I am not sure that users will recognize the slight differences for the cursors that result.
- DragDrop event of target control
Drawing
- Drawing is done on a surface called a graphics object.
- Forms and controls all provide graphics objects that allow us to draw on their surfaces. After getting a Graphics object, you can use it draw lines, fill shapes, draw text and so on.
- clauses needed for drawing
- You need to add using clauses for the System drawing namespaces:
- This gives you access to a library of drawing routines used by .NET known as GDI+. These are found in the file System.Drawing.dll.
- graphics object
- In order to draw on a graphics object we need to create four other types of objects
- Pen Used to draw lines, outlines and polygons, including rectangles, arcs, and pies Brush Used to fill enclosed surfaces with patterns, colors, or bitmaps. Font Used to draw text Color Used to describe the color used to draw an object.
- Paint event
- You can use an event handler for the Paint event of the form (or of another control) to draw on a Graphics object
- The Paint event and persistent graphics
- The form and its controls have each got Paint events that run when the form or control needs to be redrawn. You can see this effect by dragging another form in front of the form you are drawing on, the Paint event will redraw what was on the form as the other form passes. The problem here is that the instructions of what to draw need to be spelt out in the code for the Paint event handler.
- It is possible to draw on the form’s surface independently of the Paint event but the next time that the paint event runs the independent drawing will vanish.
- If we have these two event handlers, then when we click Button5 we will see a large blue ellipse but if we need to repaint the form, say by minimizing it and restoring it, we will see a brown rectangle but no blue ellipse.
- The lesson from this is that if we want graphics that persist then we will need to make the graphic displays happen in the Paint event handler.
- Pen
- A Pen is used to draw lines, outlines and shapes
- <!-- /* Font Definitions */ @font-face {font-family:Arial; panose-1:2 11 6 4 2 2 2 2 2 4; This piece of code creates a new Pen object and uses it to draw a blue line from the position (30,30) to the position (110,100) with a line width of 4. Note that we also need to create new Point objects.
- Brush
- A Brush is used to fill enclosed surfaces with patterns, colors, or bitmaps
- The Brush class exists only to be inherited from, you cannot make Brush objects using the Brush class itself. Therefore we make Brush objects from classes that inherit from the Brush class. C# gives us classes such as; SolidBrush, TextureBrush, and LinearGradientBrush are some of the classes used for creating brushes, they all inherit from the Brush class.
- Brushes are used to fill graphics shapes such as rectangles, ellipses, pies, polygons, and paths. The SolidBrush class defines a brush made up of a single color. The TextureBrush gives a Brush that can fill the interior of a shape with an image. The LinearGradientBrush gives some special effects, it encapsulates both two-color gradients and custom multi-color gradients. Other Brush classes give different effects.
- Font
- To display text on the drawing surface we use the DrawString() method. The arguments for the DrawString() method require the test string to display, a font object, a brush and a position at which to start displaying the text. The font object has properties for style, font name and size.
- The two examples below have the same result, the difference is that the new Brush is created in a separate line in the top example and it is created in the argument list in the second example. This does not cause any difference in the way the code works.
- created in separate line
- created in the argument list
- Color
- Drawing Persistent Graphics
- This project looks at how to change what is shown by the form’s paint method in response to what the user does at run time. It also looks at storing information to disk so that what the user did can be recovered next time the program is used. There are three forms in the project;
- the first draws circles in response to mouse clicks but the circles vanish if the form is repainted.
- The second form saves information about the circles to an ArrayList and uses the saved information to tell the form’s paint event handler how to draw the circles if the form needs repainting.
- The third form saves the ArrayList information to a file on the hard disk and can re-open this file and rebuild the ArrayList so that it can redraw a previous collection of circles.
- 1 Temporary circles
- In the first form, form1 we draw a circle each time the mouse is clicked. However we do this in the MouseUp event handler, not on the paint event handler so if the form has to repaint itself the circles will get lost.
- 2 Circles using the Paint event handler
- mouse was clicked to an ArrayList
- user clicks the mouse we add the point at which the mouse was clicked to an ArrayList containing a collection of points. We also ask the form to draw the ellipse.
- circles are drawn in two different event handler
- In the form’s Paint event handler we look at each point stored in the ArrayList and draw a circle for that point.. This means that we recreate the points that first got drawn on the form. In actual fact just to demonstrate that the circles are drawn in two different event handlers I have made them different diameters so the display is just slightly different.
- mouse was clicked to an ArrayList
- 3. way of extending the logic
- The drawback to form2 is that the drawing is lost when we exit the program. Form3 shows a way of extending the logic in form2 so that the information stored in the array list is saved to a text file if we use the Save menu option, as well if we use the Open menu option we can open the file again, recover the saved shape information and use it to redraw the set of shapes.
- ColorPoint
- This class has a constructor that can make a ColorPoint object from information in a string of text and a ToString() method that can store the information about a ColorPoint object in a string. When we save ColorPoint objects to a text file we use the ToString() method to store the information about each object as a string. When we open the text file and want to make some ColorPoint objects we use the ColorPoint() constructor with the string argument to do this.
- how form3 uses the ColorPoint class
- 1. Saving the points to a file:
- 2. Opening the file and getting the ColorPoint information
File Handling
Menus and Dialogs
- a main menu component Each menu caption you add is stored in your form class as a MenuItem reference.
- code for menu options
- Font style choices and other situations where several values may be true at once use a form of coding known as bitfields. There is an example program in the EnumAndBitfield folder and a further example in the MenusExample application.
- Context menus
- To add a context or popup menu drop a context menu component onto the form. Again it shows in a bar below the form. To add menu items to it click on the component and the bar at the top of the form will allow you to type in context menu items. Writing code for the context menu follows the same pattern as for the main menu.
- Running code before a sub-menu opens
- How should we enable or disable the Cut, Copy and Paste menu options of the Edit menu?
- The code to do this runs when the top level Edit menu item is clicked but the event we need to use is the Popup event NOT the Click event for this menu item.
- We decide on enabling or disabling the options based on whether there is selected text in the textbox (for Cut and Copy) and whether there is text stored in the Clipboard (Paste).
- MessageBoxes
- Dialog boxes
- File Open and Save dialog boxes
- Opening, Reading from and Writing to files
Declare Method
- Public void readEmployee (string name) Public ArrayList readEmployee (string name) ArrayList AL = ::Return xxx;Close():
Imagens e arquivos do mapa
Informações
- Descrição
- Graduate diploma Graduate Diploma in Computing Mapa Mental sobre Part C 60%, criado por Freda Fung em 08-11-2016.
- Criado por
- Freda Fung
- Visualizações
- 1
- Avaliação
Mais sobre Input, Output and File Handling
















































































