You are on page 1of 40

SIKKIM MANIPAL UNIVERSITY

BT0082 Visual Basic: SET 1 & SET 2

Mohd.Afnan Roll.no:540910075 Course: BSc.IT Semester: 4

BT0082 Visual Basic: SET 1

1. Describe the importance and usage of .NET Framework in Visual Studio. Ans. The .NET Framework (pronounced dot net framework) defines the environment that you use to execute Visual Basic .NET applications and the services you can use within those applications. One of the main goals of this framework is to make it easier to develop applications that run over the Internet. However, this framework can also be used to develop traditional business applications that run on the Windows desktop. To develop a Visual Basic .NET application, you use a product called Visual Studio .NET

(pronounced Visual Studio dot net). This is actually a suite of products that includes the three programming languages described in table 1.1. In this book, of course, youll learn how to use Visual Basic .NET, which is designed for rapid application development. Visual Studio also includes several other components that make it an outstanding development product. One of these is the Microsoft Development Environment, which youll be introduced to in a moment. Another is the Microsoft SQL Server 2000 Desktop Engine (or MSDE). MSDE is a database engine that runs on your own PC so you can use Visual Studio for developing database applications that are compatible with Microsoft SQL Server. SQL Server in turn is a database management system that can be used to provide the data for large networks of users or for Internet applications. The two other languages that come with Visual Studio .NET are C# and C++. C# .NET (pronounced C sharp dot net) is a new language that has been developed by Microsoft especially for the .NET Framework. Visual C++ .NET is Microsofts version of the C++ language that is used on many platforms besides Windows PCs. In this figure, you can see that Visual Studio .NET can be used on any PC that runs Windows 2000 or later. You can also see that the applications that are developed with Visual Studio .NET can be run on any PC that runs Windows 98 or later, depending on which .NET components are used by the application. From a practical point of view, though, you can assume that the applications that you develop with Visual Basic .NET will be run on PCs that are using Windows 2000 or later. This figure also shows that Visual Basic .NET comes in an inexpensive Standard Edition that includes only the Visual Basic language, not C# or C++. All but one of the Visual Basic features presented in this book work with the Standard Edition as well as the full Visual Studio .NET. Although the three languages shown in this figure are the only three programming

languages you can use within Visual Studio .NET, other vendors are free to develop languages for the .NET Framework. For example, Fujitsu has already developed a version of COBOL for the .NET Framework.

2. Explain various basic data types and variables in Visual Basic. Ans. Basic Data Types and Their Mapping to the CTS (Common Type System) There are two kinds of data types in VB.Net 1. Value type (implicit data types, Structure and Enumeration) 2. Reference Type (objects, delegates)

Value types are passed to methods by passing an exact copy while Reference types are passed to methods by passing only their reference (handle). Implicit data types are defined in the language core by the language vendor, while explicit data types are types that are made by using or composing implicit data types. As seen in the first unit, implicit data types in .net compliant languages are mapped to types in Common Type System (CTS) and CLS (Common Language Specification). Hence, each implicit data type in VB.Net has its corresponding .Net type. The implicit data types in VB.Net are:

VB.NET type Corresponding .Net type Size in

bytes description

Boolean

Boolean

Contains either True or False

Char

Char

Contains any single Unicode character enclosed in double quotation marks followed by a c, for example "x"c

Integral types

Byte

Byte

May contain integers from 0-255

Short

Int16

Ranges from -32,768 to 32,767

Integer(def

ault)

Int32

Ranges from -2,147,483,648 to 2,147,483,647

Long

Int64

Ranges from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

Floating point types

Single

Single

Ranges from 1.5 10-45 to 3.4 1038 with 7 digits precision. Requires the suffix 'f' or 'F'

Double(def ault)

Double

Ranges from 5.0 10-324 to 1.7 10308 with 15-16 digits precision.

Decimal

Decimal

12

Ranges from 1.0 10-28 to 7.9 1028 with 28-29 digits precision. Requires the suffix 'm' or 'M'

Variables During the execution of program, data is temporarily stored in memory. A variable is the name given to a memory location holding particular type of data. So, each variable has associated with it a data type and value. In VB.Net, a variable is declared as: Dim <variable> as <data type> Example: Dim i As Integer The above line will reserve an area of 4 bytes in memory to store integer type values, which will be referred in the rest of program by identifier 'i'. You can initialize the variable as you declare it (on the fly) and can also declare/initialize multiple variables of same type in a single statement.

3. Write a VB program to find and display the greatest of three numbers. The input

should be taken through a form based application and the greatest number should be displayed in a textbox on the form. Ans. If...Then...Else is also an statement, you can use it under other If...Then...Else statements, like: If i>5 Then ' line 1 If i=6 Then ' line 2 Console.WriteLine("Ok, 6 is also closer to 5") Else ' line 4 Console.WriteLine("Oops! i is greater than 5 but not 6") End If Console.WriteLine("Thanks God, i finally becomes greater than 5") Else ' line 8 Console.WriteLine("Missed...When will i become 5 or closed to 5?") End If

4. Develop a form based interface to demonstrate the usage of combo box and list box controls. Ans. Figure below shows you how to work with combo boxes and list boxes. In the form at the top of this figure, a combo box lets the user select a number that represents the life of an asset and a list box displays the depreciation amount for each year of the assets life. To use this form, the user enters the initial cost of the asset and the final value of the asset (which is often zero) in the text boxes. Then, the user selects the life of the asset from the drop-down list of the combo box or enters the number of years into that box. Last,

the user clicks on the Calculate button to display the year and depreciation amounts in the list box. This figure also lists some of the properties and methods youre likely to use as you work with combo boxes and list boxes. To get the index value of the item that the user selects, for example, you can use the SelectedIndex property. And to get the value of the selected item, you can use the SelectedItem property. Youll see coding examples that use these properties in the next figure (figure 4.11). One property that applies only to a combo box is the DropDownStyle property. This property determines how the combo box functions. The default is DropDown, which means that the user can either click on the drop-down arrow at the right side of the combo box to display the drop-down list and select an item, or he can enter a value directly into the text box portion of the combo box. Note that the value the user enters doesnt necessarily have to be a value that appears in the list. If you want to restrict user entries to just the values in the list, you can set the DropDownStyle property to DropDownList. Then, the user can only select a value from the list or enter a value that appears in the list. The third option for the DropDownStyle property is Simple. Like the DropDown setting, this setting lets the user enter any value into the text box portion of the control. However, instead of having to click on an arrow to display the list, the list is always visible. When you work with the items in a list box or combo box, you should realize that youre actually working with the items in a collection. To refer to this collection, you use the Items property of the control. Then, you can use the properties and methods that the .NET Framework provides for working with collection objects to work with the items in the collection. The most common properties and methods are summarized in this figure. The most common event for working with combo boxes and list boxes is the

SelectedIndexChanged event. This event occurs when the value of the SelectedIndex property changes, which is when the user selects a different item from the list. For a combo box, you can also use the TextChanged event to detect when the user enters a value into the text box portion of the control. Keep in mind, though, that this event will occur each time a single character is added, changed, or deleted.

5. Explain the concept of Exceptions in .NET environment. Ans. .NET implements a systemwide, comprehensive approach to exception handling. As noted in the chapter introduction, instead of an error number, there is an exception object. This object contains information relevant to the error, exposed as properties of the object. Later youll see a summary of the properties and the information they expose in a table. Such an object is an instance of a class that derives from a class named System.Exception. As shown later, a variety of subclasses of System.Exception are used for different circumstances. Important Properties and Methods of an Exception The Exception class has properties that contain useful information about the exception, as shown in the following table:

Property Description HelpLink A string indicating the link to help for this exception InnerException Returns the exception object reference to an inner (nested) exception Message

A string that contains a description of the error, suitable for displaying to users Source

A string containing the name of an object that generated the error StackTrace

A read-only property that holds the stack trace as a text string. The stack trace is a list of the pending method calls at the point at which the exception was detected. That is, if MethodA called MethodB, and an exception occurred in MethodB, the stack trace would contain both MethodA and MethodB. TargetSite

A read-only string property that holds the method that threw the exception

The two most important methods of the Exception class are as follows:

Method Description GetBaseException Returns the first exception in the chain ToString

Returns the error string, which might include as much information as the error message, the inner exceptions, and the stack trace, depending on the error

6. Describe the process of compiling and running a Visual Basic application. Ans. Figure below shows how an application is compiled and run when using Visual Basic .NET. To start, you use Visual Studio .NET to create a project, which is made of one or more source files that contain Visual Basic statements. Most simple projects consist of just one source file, but more complicated projects can have more than one source file. A project may also contain other types of files, such as sound files, image files, or simple text files. As the figure shows, a solution is a container for projects, which youll learn more about in a moment. Description 1.The programmer uses Visual Studios Integrated Development Environment to create a project, which includes one or more Visual Basic source files. In some cases, a project may contain other types of files, such as graphic image files or sound files.

A solution is a container that holds projects. Although a solution can contain more than one project, the solution for most simple applications contains just one project. So you can think of the solution and the project as essentially the same thing. 2. The Visual Basic compiler translates or builds the source code into Microsoft Inter-mediate Language (MSIL), or just Intermediate Language (IL). This language is stored on disk in an assembly that also contains references to the classes that the application requires. An assembly is simply an executable file that has an .exe or .dll extension. 3. The assembly is then run by the .NET Frameworks Common Language Runtime. The CLR manages all aspects of how the assembly is run, including converting the Intermediate Language to native code that can be run by the operating system, managing memory for the assembly, enforcing security, and so on.

7. What do you mean by namespaces? Explain. Ans. Namespaces in VB.Net A namespace is simply a logical collection of related classes in VB.Net. The application related classes (like those related with database activity for example) can be bundled in a named collection and hence it is called as a namespace (e.g., DataActivity). VB.Net does not allow two classes with the same name to be used in a program. The sole purpose of using namespaces is to prevent the name conflict, which may happen if working with a large number of classes. It is the same case in the Framework Class Library (FCL). For example, it is highly possible that the Connection Class in DataActivity

conflicts with the Connection Class of InternetActivity. To avoid this, these classes are made part of their respective namespace. The fully qualified name of these classes will be DataActivity.Connection and InternetActivity.Connection, hence resolving any ambiguity for the compiler. In the second line of the code, there is a declaration classes (enclosed in Namespace...End Namespace block) which are part of the MyHelloWorldApplication namespace.

The VB.Net namespaces have no physical mapping. The namespace may contain modules, classes, interfaces, events, exceptions, delegates and even other namespaces which are known as "Internal namespace". These internal namespaces can be defined like this:

Namespace MyHelloWorldApplication ... End Namespace

Namespace Parent Namespace Child ... End Namespace End Namespace

8. Write a VB program to print the day of the week taking the numbers 1 to 7 as input using SelectCase statement. Ans. Below program is using console for inputs and output. Depending on the user Input and Select case statements, program decides the day of the week and displays the results on the console.

Module Module1

Sub Main() Dim Day As Integer Console.Clear() Console.WriteLine(" * * * Console Application to Display Day of Week * * * ") Console.WriteLine("Enter Number from 1 to 7") Day = Console.ReadLine()

Select Case Day Case 1 Console.WriteLine("Monday") Case 2 Console.WriteLine("Tuesday") Case 3 Console.WriteLine("Wednesday") Case 4 Console.WriteLine("Thursday") Case 5 Console.WriteLine("Friday") Case 6 Console.WriteLine("Saturday") Case 7 Console.WriteLine("Sunday") Case Else

Console.WriteLine("Invalid Input Detected") End Select Console.Read() End Sub

End Module

9. Design a form based application using labels, text boxes, and buttons to perform basic arithmetic operations on integers. Ans.

This program demonstrates the basic arithmetic function. There are two text boxes to input the 2 operands required for calculation and combo box to select the type of arithmetic operations to be performed. The operations can be either +, -, *, / and Mod. On click of the = button, program calculates and displays the result in the third textbox. Public Class FormBT0082

Private Sub cmdEquals_Click(ByVal sender As System.Object, ByVal e As System. EventArgs) Handles cmdEquals.Click

Select Case cboOp.Text

Case "+" txtResults.Text Convert.ToInt16(txtNum1.Text) + Convert.ToInt16(txtNum2.Text)

Case "-" txtResults.Text Convert.ToInt16(txtNum1.Text) - Convert.ToInt16(txtNum2.Text)

Case "*" txtResults.Text Convert.ToInt16(txtNum1.Text) * Convert.ToInt16(txtNum2.Text)

Case "/" txtResults.Text Convert.ToInt16(txtNum1.Text) / Convert.ToInt16(txtNum2.Text)

Case "Mod" txtResults.Text Convert.ToInt16(txtNum1.Text) Mod Convert.ToInt16(txtNum2.Text)

End Select End Sub

Private Sub FormBT0082_Load(ByVal sender As System.Object, ByVal e As System. EventArgs) Handles MyBase.Load cboOp. Items . Add ("+") cboOp. Items . Add (" -) cboOp. Items . Add (" *") cboOp. Items . Add (" /")

cboOp. Items. Add ( "Mod" )

End Sub End Class

10. Describe the structured Exception handling keywords. Ans. Structured-Exception-Handling Keywords Structured exception handling depends on several new keywords in VB 2005: Begins a section of code in which an exception might be generated from a code error. This section of code is often called a Try block. In some respects, this would be the equivalent of an On Error statement in VB6. However, unlike an On Error statement, a Try statement does not indicate where a trapped exception should be routed. Instead, the exception is automatically routed to a Catch statement (discussed next). Begins an exception handler for a type of exception. One or more Catch code blocks follow a Try block, with each Catch block catching a different type of exception. When an exception is encountered in the Try block, the first Catch block that matches that type of exception receives control. A Catch statement is analogous to the line label used in a VB6 On Error statement, but the ability to route different types of exceptions to different Catch statements is a radical improvement over VB6. Contains code that runs when the Try block finishes normally, or when a Catch block receives control and then finishes. That is, the code in the Finally block always runs, regardless of whether an exception was detected. Typically,

the Finally block is used to close or dispose of any resources, such as database connections, that might have been left unresolved by the code that had a problem. There is no equivalent of a Finally in VB6.

Generates an exception. This is similar to Err.Raise in VB6. Its usually done in a Catch block when the exception should be kicked back to a calling routine or in a routine that has itself detected an error such as a bad argument passed in.

BT0082 Visual Basic: SET 2

1. Describe the Data Form Wizard in Visual Studio .NET. Ans. Visual Studio .NET and the Data Form Wizard VB.Net allows you many ways to connect to a database or a data source. The technology used to interact with a database or data source is called ADO.NET. The ADO parts stands for Active Data Objects which, admittedly, doesnt explain much. But just like System was a Base Class (leader of a hierarchy, if you like), so is ADO. Forming the foundation of the ADO Base Class are five other major objects:

Well see just what these objects are, and how to use them, as we go along. But we can make a start on the ADO.NET trail by creating a simple Address Book project. All well do is see how to use ADO to open up the database you downloaded, and scroll through each entry. What were going to be doing is to use a Wizard to create a program that reads the database and allows us to scroll through it. The wizard will create a Form for us, and allow us to add buttons to the form so that the data can be edited, updated, and deleted.

2. Describe the concept of record navigation in VB.NET. Ans. Record Navigation (i) Move Back One Record at a Time To move backwards through the DataSet, we need to decrement the inc counter. This means is deducting 1 from whatever is currently in inc. But we also need to check that inc doesn't go past zero, which is the first record in the DataSet. Here's the code to add to your btnPrevious: If inc > 0 Then inc = inc 1 NavigateRecords() Else MsgBox("First Record") End If So the If statement first checks that inc is greater than zero. If it is, inc gets 1 deducted from. Then the NavigateRecords() subroutine gets called. If inc is zero or less, then we display a message. When you've finished adding the code, test your program out. Click the Previous button first. The message box should display, even though no records have been loaded into the textboxes. This is because the variable inc has a value of -1 when the form first loads. It only gets moved on to zero when the Next button is clicked. You could amend your IF Statement to this: If inc > 0 Then inc = inc - 1

NavigateRecords() ElseIf inc = -1 Then MsgBox("No Records Yet") ElseIf inc = 0 Then MsgBox("First Record") End If This new If Statement now checks to see if inc is equal to minus 1, and displays a message if it does. It also checks if inc is equal to zero, and displays the "First Record" message box. (ii) Moving to the Last Record in the DataSet To jump to the last record in the DataSet, you only need to know how many records have been loaded into the DataSet - the MaxRows variable in our code. You can then set the inc counter to that value, but minus 1. Here's the code to add to your btnLast: If inc <> MaxRows - 1 Then inc = MaxRows - 1 NavigateRecords() End If The reason we're saying MaxRows - 1 is that the row count might be 5, say, but the first record in the DataSet starts at zero. So the total number of records would be zero to 4. Inside of the If Statement, we're setting the inc counter to MaxRows - 1, then calling the NavigateRecords() subroutine. That's all we need to do. So run your program. Click the Last button, and you should see the last record displayed in your textboxes.

(iii) Moving to the First Record in the DataSet

Moving to the first record is fairly straightforward. We only need to set the inc counter to zero, if it's not already at that value. Then call the Sub: If inc <> 0 Then inc = 0 NavigateRecords() End If Add the code to your btnFirst. Run your program and test out all of your buttons. You should be able to move through the names in the database, and jump to the first and last records. As yet, though, we don't have a way to add new records, to update records, or to delete them. Let's do that next.

3. Explain the theory behind declaring arrays in VB.NET. Ans. Declaring Arrays in Visual Basic Arrays occupy space in memory. The programmer specifies the array type and the number of elements required by the array so that the compiler may reserve the appropriate amount of memory. Arrays may be declared as Public (in a code module), module or local. Module arrays are declared in the general declarations using keyword Dim or Private. Local arrays are declared in a procedure using Dim or Static. Array must be declared explicitly with keyword "As". There are two types of arrays in Visual Basic namely: Fixed-Size Array: The size of array always remains the same-size doesn't change during the program execution. Dynamic Array: The size of the array can be changed at the run time- size changes

during the program execution. Fixed-Size Arrays When an upper bound is specified in the declaration, a Fixed-array is created. The upper limit should always be within the range of long data type. Declaring a fixed-array Dim numbers(5) As Integer In the above illustration, numbers is the name of the array, and the number 6 included in the parentheses is the upper limit of the array. The above declaration creates an array with 6 elements, with index numbers running from 0 to 5. If we want to specify the lower limit, then the parentheses should include both the lower and upper limit along with the To keyword. Example Dim numbers (1 To 6) As Integer In the above statement, an array of 10 elements is declared but with indexes running from 1 to 6. A public array can be declared using the keyword Public instead of Dim as shown below. Public numbers(5) As Integer

4. Describe the mechanism of creating transparent images using ImageList Control. Ans. Creating Transparent Images The ImageList control has a MaskColor property whose value determines the color that should be considered transparent when you're performing graphical operations on individual ListImage objects or when you're displaying images inside other controls. By default, this is the gray color (&HC0C0C0), but you can change it both at design time in

the Color tab of the Properties dialog box and at run time via code. When a graphical operation is performed, none of the pixels in the image that are the color defined by MaskColor are transferred. To actually display transparent images, however, you must ensure that the UseMaskColor property is set to True, which is its default value. You can modify this value in the General tab of the Properties dialog box or at run time via code: ' Make white the transparent color. ImageList1.MaskColor = vbWhite ImageList1.UseMaskColor = True

5. Explain the design time property settings of a ListView Control. Ans. Setting Design Time Properties While you can use the regular Properties window to set most properties of a ListView control, it's surely preferable to use a ListView control's custom Properties dialog box, shown in Figure.

6. Describe the concept of setting a connection string with an example. Ans. Setting a Connection String

There are Properties and Methods associated with the Connection Object, of course. We want to start with the ConnectionString property. This can take many parameters. Fortunately, we only need a few of these. We need to pass two things to our new Connection Object: the technology we want to use to do the connecting to our database; and where the database is. (If your database was password and user name protected, you would add these two parameters as well. Ours isn't, so we only need the two.) The technology is called the Provider; and you use "Data Source" to specify where your database is. This should be entered on the same line, and not two as it is below. So add this to your code: con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source = C:\AddressBook.mdb" Notice the two parts, separated by a semi-colon: 1st Part: PROVIDER=Microsoft.Jet.OLEDB.4.0 2nd Part: Data Source = C:\AddressBook.mdb The first part specifies which provider technology we want to use to do the connecting (JET). The second part, typed after a semi-colon, points to where the database is. In the above code, the database is on the C drive, in the root folder. The name of the Access file we want to connect to is called AddressBook.mdb. (Note that "Data Source" is two words, and not one.) But your coding window should now look like this:

This assumes that you have copied the AddressBook database over to the root folder of your C Drive. If you've copied it to another folder, change the "Data Source" part to match. For example, if you copied it to a folder called "databases" you'd put this: Data Source = C:\databases\AddressBook.mdb In our code , though, ConnectionString is a property of the con variable. The con variable holds our Connection Object. We're passing the Connection String the name of a data provider, and a path to the database.

Private Sub btnLoad_Click(ByVal Sender as Object,_ ByVal e as System.EventArgs) _ Handles btnLoad.Click Dim con as new OleDb.OleDbConnection Con.ConnectionString = Provider = Microsoft.Jet.OLEDB.4.0; DataSource = C:\AddressBook.mdb 7. Describe the process of adding, updating, and deleting records with an example. Ans. Add, Update and Delete Records In the last section, you learned how to move through the records in your DataSet, and how to display the records in Textboxes on your form. In this lesson, we'll see how to add new records, how to delete them and how to Update a records.

Before we start the coding for these new buttons, it's important to understand that the DataSet is disconnected from the database. What this means is that if you're adding a new record, you're not adding it to the database: you're adding it to the DataSet! Similarly, if you're updating or Deleting, you are doing it to the DataSet, and NOT to the database. After you have made all of your changes, you THEN commit these changes to the database. You do this by issuing a separate command. But we'll see how it all works. You'll need to add a few more buttons to your form - five of them. Change the Name properties of the new Buttons to the following:

Change the Text properties of the buttons to "Add New Record ", "Commit Changes", "Update Record ", "Delete Record", and "Clear/Cancel". Your form might look something like this:

(i) Updating a Record To reference a particular column (item) in a row of the DataSet, the code is this: ds.Tables("AddressBook").Rows(2).Item(1) That will return whatever is at Item 1 on Row 2. As well as returning a value, you can also set a value. You do it like this: ds.Tables("AddressBook").Rows(2).Item(1) = "Jane" Now Item 1 Row 2 will contain the text "Jane". This won't, however, affect the database!

The changes will just get made to the DataSet. To illustrate this, add the following code to your btnUpdate: ds.Tables("AddressBook").Rows(inc).Item(1) = txtFirstName.Text ds.Tables("AddressBook").Rows(inc).Item(2) = txtSurname.Text MsgBox("Data updated") Run your program, and click the Next Record button to move to the first record. "John" should be displayed in your first textbox, and "Smith" in the second textbox. Click inside the textboxes and change "John" to "Joan" and "Smith" to "Smithy". (Without the quotes). Now click your Update Record button. Move to the next record by clicking your Next Record button, and then move back to the first record. You should see that the first record is now "Joan Smithy". (ii) Add a New Record Adding a new record is slightly more complex. First, you have to add a new Row to the DataSet, then commit the new Row to the Database. But the Add New Record button on our form is quite simple. The only thing it does is to switch off other buttons, and clear the textboxes, ready for a new entry. Here's the code for your Add New Record button: btnCommit.Enabled = True btnAddNew.Enabled = False btnUpdate.Enabled = False btnDelete.Enabled = False txtFirstName.Clear() txtSurname.Clear() So three buttons are switched off when the Add New Record button is clicked, and one is switched on. The button that gets switched on is the Commit Changes button. The Enabled property of btnCommit gets set to True. But, for this to work, you need to set it to False when the form loads. So return to your Form. Click btnCommit to select it. Then locate the Enabled Property in the Properties box. Set it to False. When the Form

starts up, the button will be switched off. The Clear/Cancel button can be used to switch it back on again. So add this code to your btnClear: btnCommit.Enabled = False btnAddNew.Enabled = True btnUpdate.Enabled = True btnDelete.Enabled = True inc = 0 NavigateRecords() We're switching the Commit Changes button off, and the other three back on. The other two lines just make sure that we display the first record again, after the Cancel button is clicked. Otherwise the textboxes will all be blank. (iii) Delete a Record from a Database The code to delete a record is a little easier than last time. Double click your btnDelete and add the following: Dim cb As New OleDb.OleDbCommandBuilder(da) ds.Tables("AddressBook").Rows(inc).Delete() MaxRows = MaxRows - 1 inc = 0 NavigateRecords() da.Update(ds, "AddressBook") You've met most of it before. First we set up a Command Builder. Then we have this line: ds.Tables("AddressBook").Rows(inc).Delete() Just as there is an Add method of the DataSet Rows property, so there is a Delete method. You don't need anything between the round brackets, this time. We've specified the Row to delete with: Rows(inc) The inc variable is setting which particular Row we're on. When the Delete method is called, it is this row that will be deleted. However, it will only be deleted from the DataSet. To delete the row from the underlying

database, we have this again: da.Update(ds, "AddressBook")

8. Explain the usage of variants in VB.NET. Ans. Arrays and Variants Visual Basic lets you store arrays in Variant variables and then access the array items using the Variant variable as if it were an array: ReDim Names(100) As String, var As Variant ' Initialize the Names array (omitted). var = Names() ' Copy the array into the Variant. Print var(1) ' Access array items through the Variant. You can even create an array of Variant elements on the fly using the Array function and store it in a Variant variable: ' Arrays returned by the Array() function are zero-based. Factorials = Array(1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800) Likewise, you can pass an array to a procedure that expects a Variant parameter and then access the elements of the array through that parameter: ' A polymorphic function that sums the values in any array Function ArraySum(arr As Variant) As Variant Dim i As Long, result As Variant For i = LBound(arr) To UBound(arr) result = result + arr(i) Next ArraySum = result End Function The most interesting feature of the preceding routine is that it works correctly with any type of numeric one-dimensional array. It even works with String arrays, but in that case you get the concatenation of all items, not their sum.

9. Describe the process of extracting and drawing images using ImageList Control. Ans. Extracting and Drawing Images If you associate an ImageList control with another common control, you usually don't have to worry about extracting and showing individual images because everything is done automatically for you. But if you want to manually display or print images, you have to learn how to use a few properties and methods from the ImageList control and its ListImage dependent objects. Extracting Individual Images Each ListImage object exposes a Picture property, which lets you extract the image and assign it to another control, typically a PictureBox or Image control: Set Picture1.Picture = ImageList1.ListImages("Cut").Picture In general, you can use the Picture property of a ListImage object whenever you would use the Picture property of a PictureBox or an Image control, as in the following example: ' Save an image to a disk file. SavePicture ImageList1.ListImages("Cut").Picture, "C:\cut.bmp" ' Display an image on the current form, zooming it by a factor ' of 4 along the X-axis, and 8 along the Y-axis. With ImageList1 PaintPicture .ListImages("Cut").Picture, 0, 0, _ ScaleX(.ImageWidth, vbPixels) * 4, ScaleY(.ImageHeight, vbPixels) * 8

End With Using the PaintPicture method, you can display any ListImage object on a form or in a PictureBox control, or you can print it to the Printer object. ListImage objects also expose an ExtractIcon method, which creates an icon out of the image and returns it to the caller. You can therefore use this method whenever an icon is expected, as in this code: Form1.MouseIcon = ImageList1.ListImages("Pointer").ExtractIcon Unlike standard collections, keys in the ListImages collection are dealt with in a case-sensitive way. In other words, "Pointer" and "pointer" are assumed to be different items.

10. Describe the runtime properties of ListView Control. Ans. Run-Time Operations While you can define the appearance of a ListView control at design time, you can fill it with data only through code. In this section, we would see how to add and manipulate data for this control.

You might also like