Mastering Microsoft Visual Basic 2008 phần 10 pot

119 309 0
Mastering Microsoft Visual Basic 2008 phần 10 pot

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Petroutsos bapp01.tex V3 - 01/28/2008 5:29pm Page 1000 1000 APPENDIX A THE BOTTOM LINE Use arrays. Arrays are structures for storing sets of data, as opposed to single-valued variables. Master It How would you declare an array for storing 12 names and another one for storing 100 names and Social Security numbers? Solution The first array stores a set of single-valued data (names) and it has a single dimension. Because the indexing of the array’s elements starts at 0, the last element’s index for the first array is 11, and it must be declared as Dim Names(11) As String The second array stores a set of pair values (names and SSNs), and it must be declared as a two-dimensional array: Dim Persons(99,1) As String Chapter 3: Programming Fundamentals Use Visual Basic’s flow-control statements. Visual Basic provides several statements for controlling the sequence in which statements are executed: decision statements, which change the course of execution based on the outcome of a comparison, and loop statements, which repeat a number of statements while a condition is true or false. Master It Explain briefly the decision statements of Visual Basic. Solution The basic decision statement in VB is the If End If statement, which executes the statements between the If and End If keywords if the condition specified in the If part is True. A variation of this statement is the If Then Else End If statements. If the same expression must be compared to multiple values and the program should execute different statements depending on the outcome of the comparison, use the Select Case statement. Write subroutines and functions. To manage large applications, we break our code into small, manageable units. These units of code are the subroutines and functions. Subroutines perform actions and don’t return any values. Functions, on the other hand, perform calcula- tions and return values. Most of the language’s built-in functionality is in the form of functions. Master It How will you create multiple overloaded forms of the same function? Solution Overloaded functions are variations of the same function with different argu- ments. All overloaded forms of a function have the same name, and they’re prefixed with the Overloads keyword. Their lists of arguments, however, are different — either in the number of arguments or in their types. Pass arguments to subroutines and functions. Procedures and functions communicate with one another via arguments, which are listed in a pair of parentheses following the procedure’s Petroutsos bapp01.tex V3 - 01/28/2008 5:29pm Page 1001 CHAPTER 4: GUI DESIGN AND EVENT-DRIVEN PROGRAMMING 1001 name. Each argument has a name and a type. When you call the procedure, you must supply values for each argument and the types of the values should match the types listed in the pro- cedure’s definition. Master It Explain the difference between passing arguments by value and passing argu- ments by reference. Solution The first mechanism, which was the default mechanism with earlier versions of the language, passes a reference to the argument. Arguments passed by reference are prefixed by the keyword ByRef in the procedure’s definition. The procedure has access to the original values of the arguments passed by reference and can modify them. The second mechanism passes to the procedure a copy of the original value. Arguments passed by value are prefixed with the keyword ByVal in the procedure’s definition. The procedure may change the values of the arguments passed by value, but the changes won’t affect the value of the original variable. Chapter 4: GUI Design and Event-Driven Programming Design graphical user interfaces. A Windows application consists of a graphical user inter- face and code. The interface of the application is designed with visual tools and consists of controls that are common to all Windows applications. You drop controls from the Toolbox window onto the form, size and align the controls on the form, and finally set their properties through the Properties window. The controls include quite a bit of functionality right out of the box, and this functionality is readily available to your application without a single line of code. Master It Describe the process of aligning controls on a form. Solution To align controls on a form, you should select them in groups, according to their alignment. Controls can be aligned to the left, right, top, and bottom. After selecting a group of controls with a common alignment, apply the proper alignment with one of the commands of the Format  Align menu. Before aligning multiple controls, you should adjust their spacing. Select the controls you want to space vertically or horizontally and adjust their spacing with one of the commands of the Format  Horizontal Spacing and Format  Vertical Spacing methods. You can also align controls visually, by moving them with the mouse. As you move a control around, a blue snap line appears every time the con- trol is aligned with another one on the form. Program events. Windows applications follow an event-driven model: We code the events to which we want our application to respond. The Click events of the various buttons are typical events to which an application reacts. You select the actions to which you want your application to react and program these events accordingly. When an event is fired, the appropriate event handler is automatically invoked. Event han- dlers are subroutines that pass two arguments to the application: the senderobject (which is an object that represents the control that fired the event) and the e argument (which carries additional information about the event). Petroutsos bapp01.tex V3 - 01/28/2008 5:29pm Page 1002 1002 APPENDIX A THE BOTTOM LINE Master It How will you handle certain keystrokes regardless of the control that receives them? Solution You can intercept all keystrokes at the form’s level by setting the form’s KeyPreview property to True. Then insert some code in the form’s KeyPress event han- dler to examine the keystroke passed to the event handler and process it. To detect the key presses in the KeyPress event handler, use an If statement like the following: If e.KeyChar = ”A” Then ’ process the A key End If Write robust applications with error handling. Numerous conditions can cause an applica- tion to crash, but a professional application should be able to detect abnormal conditions and handle them gracefully. To begin with, you should always vali date your data before you attempt to use them in your code. A well-known computer term is ‘‘garbage in, garbage out’’, which means you shouldn’t perform any calculations on invalid data. Master It How will you execute one or more statements in the context of a structured exception handler? Solution A structured exception handler has the following syntax: Try {statements} Catch ex As Exception {statements to handle exception} End Try The statements you want to execute must be inserted in the Try block of the statement. If executed successfully, program execution continues with the statements following the End Try statement. If an error occurs, the Catch block is activated, where you can display the appropriate message and take the proper actions. At the very least, you should save the user data and then terminate the application. In many cases, it’s even possible to remedy the situation that caused the exception in the first place. Chapter 5: The Vista Interface Create a simple WPF application. WPF is a new and powerful technology for creating user interfaces. WPF is one of the core technologies in the .NET Framework 3.5 and is integrated into Windows Vista. WPF is also supported on Windows XP. WPF takes advantage of the graphics engines and display capabilities of the modern computer and is vector based and res- olution independent. Master It Develop a simple ‘‘Hello World’’ type of WPF application that displays a But- ton control and Label control. Clicking the button should set the content property of a Label control to Hi There! Petroutsos bapp01.tex V3 - 01/28/2008 5:29pm Page 1003 CHAPTER 5: THE VISTA INTERFACE 1003 Solution Complete the following steps. 1. Open Visual Studio 2008 and choose File  New Project. 2. From the New Project dialog box, select WPF Application and click OK. 3. From the Toolbox, drag a Button control and Label control to Window1 on the design surface. 4. Double-click the Button control and add the following line of code to the Button1 Click event in code-behind: Label1.Content = ”Hi There!” Data-bind controls in WPF. The ability to bind controls to a data source is an essential aspect of separating the UI from the business logic in an application. Master It Data-bind a Label control to one field in a record returned from a database on your computer. Solution Complete the following steps. 1. Open Visual Studio 2008 and create a new WPF project. 2. Establish a link to an existing database on your system by opening the Server Explorer window (click the appropriate tab at the bottom of the Toolbox area of Visual Studio) and right-clicking Data Connections. Choose Add Connection from the context menu and follow the prompts. Note that you use the Microsoft SQL Server Database File option if you are planning to connect to a database created by SQL Server Express (the default database system that ships with Visual Studio 2008). 3. Open the Data Sources window by clicking the tab at the bottom of the Server Explorer window, and then click the Add New Data Source link. This opens the Data Source Con- figuration Wizard. Follow the prompts to set up the dataset. 4. Switch to code-behind (Window1.xaml.vb)forWindow1.xaml. Add the following code. Note that the ContactsDataSet, ContactsDataSetTableAdapters, and CustomersTable- Adapter names will vary according to the actual names that you have set up for your dataset. Class Window1 Dim mydataset As New ContactsDataSet Dim mydataAdapter As New ContactsDataSetTableAdapters.CustomersTableAdapter Private Sub Window1 Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded mydataAdapter.Fill(mydataset.Tables(0)) Me.DataContext = mydataset.Tables(0).Rows(0) End Sub End Class Petroutsos bapp01.tex V3 - 01/28/2008 5:29pm Page 1004 1004 APPENDIX A THE BOTTOM LINE 5. Switch back to XAML view for Window1.xaml and add the following markup (without line breaks). You may need to change the FirstName reference in the binding for Label1 to whichever database field that you want displayed: <Window x:Class=”Window1” xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml” Title=”Window1” Height=”300” Width=”300”> <Grid> <Label Margin=”38,129,47,90” Name=”Label1” Content=”{Binding Path=FirstName}” ></Label> </Grid> </Window> 6. Run the application. The contents of your nominated field from the first table indexed in your database (0) should be displayed in the Label control. Use a data template to control data presentation. WPF enables a very flexible approach to presenting data by using data templates. The developer can create and fully customize data templates for data formatting. Master It Create a data template to display a Name, Surname, Gender combination in a horizontal row in a ComboBox control. Create a simple array and class of data to feed the application. Solution Complete the following steps. 1. Add the following code to the XAML source for Window1.xaml (delete the line breaks): <Window x:Class=”Window1” xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml” Title=”Window1” Height=”300” Width=”300”> <Grid Name=”myGrid”> <Grid.Resources> <DataTemplate x:Key=”NameStyle”> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width=”60” /> <ColumnDefinition Width=”60” /> <ColumnDefinition Width=”*” /> </Grid.ColumnDefinitions> <TextBlock Grid.Column=”0” Text=”{Binding Path=FirstName}”/> <TextBlock Grid.Column=”1” Text=”{Binding Path=Surname}”/> Petroutsos bapp01.tex V3 - 01/28/2008 5:29pm Page 1005 CHAPTER 5: THE VISTA INTERFACE 1005 <TextBlock Grid.Column=”2” Text=”{Binding Path=Gender}”/> </Grid> </DataTemplate> </Grid.Resources> <ComboBox ItemTemplate=”{StaticResource NameStyle}” ItemsSource=”{Binding }” IsSynchronizedWithCurrentItem=”true” Height=”25” VerticalAlignment=”Top” Name=”ComboBox1” /> </Grid> </Window> 2. Switch to code-behind for Window1.xaml (Window1.xaml.vb) and add the following code: Class Window1 Private Class myList Dim name As String Dim surname As String Dim gender As String Public Sub New(ByVal FirstName As String, ByVal Surname As String, ByVal Gender As String) name = FirstName surname = Surname gender = Gender End Sub Public ReadOnly Property FirstName() As String Get Return name End Get End Property Public ReadOnly Property Surname() As String Get Return surname End Get End Property Public ReadOnly Property Gender() As String Get Return gender End Get End Property End Class Private Sub Window1 Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded Petroutsos bapp01.tex V3 - 01/28/2008 5:29pm Page 1006 1006 APPENDIX A THE BOTTOM LINE Dim myArray As New ArrayList myArray.Add(New MyList(”Fred”, ”Bloggs”, ”M”)) myArray.Add(New MyList(”Mary”, ”Green”, ”F”)) myArray.Add(New MyList(”Sally”, ”Smith”, ”F”)) myArray.Add(New MyList(”John”, ”Doe”, ”M”)) myArray.Add(New MyList(”Jemma”, ”Bloggs”, ”F”)) Me.DataContext = myArray End Sub End Class 3. Run the application. A combo box containing a list of the contacts should be displayed as FirstName, Surname, and Gender. Chapter 6: Basic Windows Controls Use the TextBox control as a data-entry and text-editing tool. The TextBox control is the most common element of the Windows interface, short of the Button control, and it’s used to display and edit text. You can use a TextBox control to prompt users for a single line of text (such as a product name) or a small document (a product’s detailed description). Master It What are the most important properties of the TextBox control? Which ones would you set in the Properties windows at design-time? Solution First you must decide whether you want the control to hold a single line of text or multiple text lines, and set the MultiLine property accordingly. You must also decide whether the control should wrap words automatically and then set the WordWrap and ScrollBars properties accordingly. If you want the control to display some text initially, set the control’s Text property to the desired text. At runtime you can retrieve the text entered by the user in the control, with the same property. Another property, the Lines array, allows you to retrieve individual paragraphs of text. Each paragraph can be broken into multiple text lines on the control, but each is stored in a single element of the Lines array. Master It How will you implement a control that suggests lists of words matching the characters entered by the user? Solution Use the autocomplete properties AutoCompleteMode, AutoCompleteSource, and AutoCompleteCustomSource.TheAutoComplete property determines whether the control will suggest the possible strings, automatically complete the current word as you type, or do both. The AutoCompleteSource property specifies where the strings that will be displayed will come from, and its value is a member of the AutoCompleteSource enumeration. If this property is set to AutoCompleteSoure.CustomSource, you must set up an AutoCompleteStringCollection collection with your custom strings and assign it to the AutoCompleteCustomCource property. Use the ListBox, CheckedListBox, and ComboBox controls to present lists of items. The ListBox control contains a list of items from which the user can select one or more, depending on the setting of the SelectionMode property. Petroutsos bapp01.tex V3 - 01/28/2008 5:29pm Page 1007 CHAPTER 7: WORKING WITH FORMS 1007 Master It How will you locate an item in a ListBox control? Solution To locate a string in a ListBox control, use the FindString and FindString- Exact methods. The FindString method locates a string that partially matches the one you’re searching for; FindStringExact finds an exact match. Both methods perform case- insensitive searches and return the index of the item they’ve located in the list. We usually call the FindStringExact method and then examine its return value. If an exact match was found, we select the item with the index returned by the FindStringExact method. If an exact match was not found, in which case the method returns −1, we call the FindString method to locate the nearest match. Use the ScrollBar and TrackBar controls to enable users to specify sizes and positions with the mouse. The ScrollBar and TrackBar controls let the user specify a magnitude by scrolling a selector between its minimum and maximum values. The ScrollBar control uses some visual feedback to display the effects of scrolling on another entity, such as the current view in a long document. Master It Which event of the ScrollBar control would you code to provide visual feedback to the user? Solution The ScrollBar control fires two events: the Scroll event and the ValueChanged event. They’re very similar, and you can program either event to react to the changes in the ScrollBar control. The advantage of the Scroll event is that it reports the action that caused it through the e.Type property. You can examine the value of this property in your code and react to actions such as the end of the scroll: Private Sub blueBar Scroll( ByVal sender As System.Object, ByVal e As System.Windows.Forms.ScrollEventArgs) Handles blueBar.Scroll If e.Type = ScrollEventType.EndScroll Then ’ perform calculations and provide feedback End If End Sub Chapter 7: Working with Forms Use forms’ properties. Forms expose a lot of trivial properties for setting their appearance. In addition, they expose a few properties that simplify the task of designing forms that can be resized at runtime. The Anchor property causes a control to be anchored to one or more edges of the form to which it belongs. The Dock property allows you to place on the form controls that are docked to one of its edges. To create forms with multiple panes that the user can resize at runtime, use the SplitContainer control. If you just can’t fit all the controls in a reasonably sized form, use the AutoScroll properties to create a scrollable form. Master It You’ve been asked to design a form with three distinct sections. You should also allow users to resize each section. How will you design this form? Solution The type of form required is easily designed with visual tools and the help of the SplitContainer control. Place a SplitContainer control on the form and set its Dock Petroutsos bapp01.tex V3 - 01/28/2008 5:29pm Page 1008 1008 APPENDIX A THE BOTTOM LINE property to Fill. You’ve just created two vertical panes on the form, and users can change their relative sizes at any time. To create a third pane, place another SplitContainer con- trol on one of the first control’s panes and set its Dock property to Fill, and its Orientation property to Horizontal. At this point, the form is covered by three panes, and users can change each pane’s size at the expense of its neighboring panes. Design applications with multiple forms. Typical applications are made up of multiple forms: the main form and one or more auxiliary forms. To show an auxiliary form from within the main form’s code, call the auxiliary form’s Show method, or the ShowDialog method if you want to display the auxiliary form modally (as a dialog box). Master It How will you set the values of selected controls in a dialog box, display them, and then read the values selected by the user from the dialog box? Solution Create a Form variable that represents the dialog box and then access any con- trol in the dialog box through its name as usual, prefixed by the form’s name: Dim Dlg As AuxForm Dlg.txtName = ”name” Then call the form’s ShowDialog method to display it modally and examine the DialogResult property returned by the method. If this value is OK, process the data in the dialog box, or else ignore them: If Dlg.ShowDialog = DialogResult.OK Then UserName = Dlg.TxtName End If To display an auxiliary form, just call the Show method. This method doesn’t return a value, and you can read the auxiliary form’s contents from within the main form’s code at any time. You can also access the controls of the main form from within the auxiliary form’s code. Design dynamic forms. You can create dynamic forms by populating them with controls at runtime through the form’s Controls collection. First, create instances of the appropriate controls by declaring variables of the corresponding type. Then set the properties of the vari- able that represents the control. Finally, place the control on the form by adding it to the form’s Controls collection. Master It How will you add a TextBox control to your form at runtime and assign a handler to the control’s TextChanged event? Solution Create an instance of the TextBox control, set its Visible property, and add it to the form’s Controls collection: Dim TB As New TextBox TB.Visible = True ’ statements to set other properties, ’ including the control’s location on the form Me.Controls.Add(TB) Then write a subroutine that will handle the TextChanged event. This subroutine, let’s call it TBChanged(), should have the same signature as the TextBox control’s TextChanged Petroutsos bapp01.tex V3 - 01/28/2008 5:29pm Page 1009 CHAPTER 8: MORE WINDOWS CONTROLS 1009 event. Use the AddHandler statement to associate the TBChanged() subroutine with the new control’s TextChanged event: AddHandler TB.TextChanged, New SystemEventHandler(AddressOf TBChanged) Design menus. Both form menus and context menus are implemented through the Menu- Strip control. The items that make up the menu are ToolStripMenuItem objects. The ToolStripMenuItem objects give you absolute control over the structure and appearance of the menus of your application. Master It What are the two basic events fired by the ToolStripMenuItem object? Solution When the user clicks a menu item, the DropDownOpened and Click events are fired, in this order. The DropDownOpened event gives you a chance to modify the menu that’s about to be opened. After the execution of the DropDownOpened event handler, the Click event takes place to indicate the selection of a menu command. We rarely program the DropDownOpened event, but every menu item’s Click event handler should contain some code to react to the selection of the item. Chapter 8: More Windows Controls Use the OpenFileDialog and SaveFileDialog controls to prompt users for filenames. Win- dows applications use certain controls to prompt users for common information, such as filenames, colors, and fonts. Visual Studio provides a set of controls, which are grouped in the Dialogs section of the Toolbox. All common dialog controls provide a ShowDialog method, which displays the corresponding dialog box in a modal way. The ShowDialog method returns a value of the DialogResult type, which indicates how the dialog box was closed, and you should examine this value before processing the data. Master It Your application needs to open an existing file. How will you prompt users for the file’s name? Solution First you must drop an instance of the OpenFileDialog control on the form. To limit the files displayed in the Open dialog box, use the Filter property to specify the rel- evant file type(s). To display text files only, set the Filter property to Text files|*.txt. If you want to display multiple extensions, use a semicolon to separate extensions with the Filter property; for example, the string Images|*.BMP;*.GIF;*.JPGwill cause the con- trol to select all the files of these three types and no others. The first part of the expression (Images) is the string that will appear in the drop-down list with the file types. You should also set the CheckFileExists property to True to make sure that the file specified on the control exists. Then display the Open dialog box by calling its ShowDialog method, as shown here: If FileOpenDialog1.ShowDialog = Windows.Forms.DialogResult.OK {process file FileOpenDialog1.FileName} End If To retrieve the selected file, use the control’s FileName property, which is a string with the selected file’s path. [...]... WORKING WITH OBJECTS 101 5 2 Call the New() constructor, passing the book’s ISBN as a parameter: Dim book As New Book(”9780213324543”) 3 Call the New() constructor, passing the book’s ISBN and title: Dim book As New Book(”9780213324543”, Mastering Visual Studio”) Customize the usual operators for your classes Overloading is a common theme in coding classes (or plain procedures) with Visual Basic In addition... Likewise, the TitleAuthor.AuthorID field is the foreign key to the relationship between the TitleAuthor and Authors tables Utilize the data tools of Visual Studio Visual Studio 2008 provides visual tools for working with databases The Server Explorer is a visual representation of the databases you can access from your computer and their data You can create new databases, edit existing ones, and manipulate... — you simply exit the PrintPage event handler If there are more pages to print, set the HasMorePages property to True Any static variables you use to maintain state CHAPTER 20: PRINTING WITH VISUAL BASIC 2008 103 3 between successive invocations of the PrintPage event handler, such as the page number, must be reset every time you start a new printout A good place to initialize the printout’s variables... with the attribute, which specifies the name of the table that will populate the class: Public Class Customers End Class CHAPTER 18: DRAWING AND PAINTING WITH VISUAL BASIC 2008 102 9 Each property of this table must be decorated with the attribute, which specifies the name of the column from which the property will get its value: ... method of the DataContext object, pass the name of the class as an argument, and the DataContext object will create a new instance of the class and populate it Chapter 18: Drawing and Painting with Visual Basic 2008 Display and size images The most appropriate control for displaying images is the PictureBox control You can assign an image to the control through its Image property, either at design time... newBmp.SetPixel(Bmp.Width - row - 1, Bmp.Height - col - 1, clr) Next Next To view the processed image, assign the newBmp variable to the Image property of a PictureBox control Chapter 20: Printing with Visual Basic 2008 Use the printing controls and dialog boxes To print with the NET Framework, you must add an instance of the PrintDocument control to your form and call its Print method To preview the same... Table column CHAPTER 22: PROGRAMMING WITH ADO.NET 103 5 Use the Structured Query Language for accessing tables Structured Query Language (SQL) is a universal language for manipulating tables SQL is a nonprocedural language, which specifies the operation you want to perform against a database at a high level, unlike traditional languages such as Visual Basic, which specifies how to perform the operation... some basic functions that act like operators, especially the CType() function Chapter 11: Working with Objects Use inheritance Inheritance, which is the true power behind OOP, allows you to create new classes that encapsulate the functionality of existing classes without editing their code To inherit from an existing class, use the Inherits statement, which brings the entire class into your class 101 6... data type to handle strings The String data type represents strings and exposes members for manipulating them Most of the String class’s methods are equivalent to the string-manipulation methods of Visual Basic The members of the String class are shared: they do not modify the string to which they’re applied Instead, they return a new string Master It How would you extract the individual words from... wish You can also set the appearance of the subitems (their font and color) in the same dialog box Master It How would you populate the same control with the same data at runtime? CHAPTER 10: BUILDING CUSTOM CLASSES 101 3 Solution runtime: The following code segment adds two items to the ListView1 control at Dim LItem As New ListViewItem() LItem.Text = ”Alfred’s Futterkiste” LItem.SubItems.Add(”Anders . There! Petroutsos bapp01.tex V3 - 01/28 /2008 5:29pm Page 100 3 CHAPTER 5: THE VISTA INTERFACE 100 3 Solution Complete the following steps. 1. Open Visual Studio 2008 and choose File  New Project. 2 property, which is a string with the selected file’s path. Petroutsos bapp01.tex V3 - 01/28 /2008 5:29pm Page 101 0 101 0 APPENDIX A THE BOTTOM LINE Master It You’re developing an application that encrypts. designed with visual tools and the help of the SplitContainer control. Place a SplitContainer control on the form and set its Dock Petroutsos bapp01.tex V3 - 01/28 /2008 5:29pm Page 100 8 100 8 APPENDIX

Ngày đăng: 12/08/2014, 21:20

Tài liệu cùng người dùng

Tài liệu liên quan