Sie sind auf Seite 1von 20

1.

Getting Started
In this book, we work under the basic assumption that you have no inkling about any of the programming languages, and VisualBasic.Net in particular. But, you would invariably have heard people fantasizing about the great new product called Visual Studio.Net, which is in the reckoning to bring about a revolution in the software industry. So, let us get to the meat of this product. We shall gain a meticulous understanding of this language and its features, and only then shall we decide whether the claims made by the populace are justified or not. We could keep extolling the virtues of the finer things in life, but we'd rather get down to brass-tacks straightaway. We assume that you have a copy of Visual Studio.Net installed on your machine. To launch Visual Studio, click on the ubiquitous Start Button in Windows. (In our case, we have installed Windows 2000). Then, click on Programs, followed by Microsoft Visual Studio .Net. Finally, select the option of Microsoft Visual Studio .Net. This is shown in the Screen 1.1.

Screen 1.1
Shortly thereafter, a window pops up, showing Visual Studio.Net in all its glory, as shown in screen 1.2.

Screen 1.2
Hey, hang on! Could there be something amiss with what you are doing? Your copy of Visual Studio .Net could be displaying something totally different!! Yes, this could be a distinct possibility! One of the salient features of present day software is that it can be customized to a large extent. This is why the final appearance of a product could be drastically different from what it originally looked like, when freshly taken out of the box. Thus, the screen 1.2 will never look identical on all the machines. We shall explicate these differences in due course, but for the moment, we are exceedingly inclined towards embarking upon the development of a small application or project. But before venturing any further, close all the child windows by clicking on the x sign. Then, click on the menu option File, followed by New, and finally Project. This becomes evident in screen 1.3.

Screen 1.3
The above actions will result in the display of the Dialog box titled "New Project". This is shown in screen 1.4. The advantage of using Visual Studio .Net is that diverse applications, each using a different programming language, can be developed simultaneous, under a single streamer. This explains why three language options are present in the first pane of the dialog box, viz. Visual Basic, Visual C# and Visual C++.

Screen 1.4
The option of Visual Basic project is listed first. Hence, it is highlighted by default. This signifies the priorities of Microsoft, and is the very raison de etr of this book!

A perfect analogy for Visual Studio .Net is that of a glass, which can be used to drink either water or juice or wine. In a similar fashion, under the single roof of Visual Studio .Net, various programs developed in different languages, can be written. The language used is simply not an issue. The second pane titled 'Templates' determines the type of application that would eventually be created. This could be an executable file running under Windows, or a Web Application running a web server. Since we are nave about this product, we select the option of Windows Application. This option is selected by default. The next task is to specify a name for the project. We have chosen the name 'vvv', since we sincerely believe that it will bring us good tidings on our very first application. We have used our newly created folder called 'v1' as the location for creating the application. You are at liberty to choose any folder that you fancy.

Screen 1.5
After specifying all the details as shown in screen 1.5, click on the OK button. This brings us to Screen 1.6, where we encounter an empty form.

Screen 1.6
Now, in order to view the output of our handiwork, click on the menu option Debug, and then on Start. This is shown in screen 1.7.

Screen 1.7
This ignites the excitement of Visual Studio .Net, and it starts processing the request. Finally, as the outcome of the operation, it displays an empty form, as seen in screen 1.8. This is no mean achievement for people like us, considering the fact that we have not written even a single line of code yet!

Screen 1.8
Close this form window by clicking on the x sign on the right hand side. This will revert us back to the form in Visual Studio .Net. The next task that we venture upon is, to display a button on the form. To accomplish this, click on the menu option View, and then, on the option of ToolBox, as shown in screen 1.9.

Screen 1.9
This option brings up a toolbox containing a list of objects or controls. The toolbox window is visible on the left hand side of the screen, as revealed in screen 1.10.

Screen 1.10
Now, simply click on the control labelled as Button to select it, and then, drag and drop it into the form. Screen 1.11 displays the position where we have dropped our button.

Screen 1.11
Then, run the application in the customary manner by clicking on the menu Debug, and then, click on Start. Screen 1.12 confirms that the form now contains the button in it. Pat on the back! Having covered just a couple of pages, we have already placed a button on the form.

Screen 1.12
The shortcoming of our present endeavour is that, we are clueless about what is going on behind the scenes. Clicking on the OK button in the New Project dialog box, results in the generation of considerable amount of code by the Visual Studio .Net framework. Apparently, we have merely clicked on the ToolBox, which is a User Interface tool; and then, we have dragged and dropped a button in the form. However, in reality, ample code has been generated in the background to accomplish this seemingly simple task. We are convinced that prior to forging ahead with the task of building complex applications using Visual Studio .Net, there is a need for discerning the code that it generates. Also, along the way, we shall keep reverting back to the Visual Studio .Net framework, to demonstrate as to how it has made a programmer's life more easygoing. However, you have to learn a programming language that is to be used with it, since it is a fundamental fact that Visual Studio .Net cannot build customized applications by itself. It is the task of the programmer to program it to satisfy the specific requirements. So, we start by writing the smallest Visual Basic program. As is customary in all our books, we shall refrain from attempting to impress you with our knowledge of programming. Instead, we shall proceed systematically, a single step at a time. So, here we go! First, create a folder named il on your hard disk. Then, using a text editor such as Notepad, create a file called a.vb, with the following contents in it: a.vb Module zzz End Module To execute the above code, go to the Visual Studio .NET Command Prompt (Start-> Program-> Visual Studio .Net-> Visual Studio .Net Tools-> Visual Studio .NET Command Prompt), and run a program called vbc. We achieve it as follows: c:\il>vbc a.vb This action of ours results in the following error message:

vbc : error BC30420: 'Sub Main' was not found in 'a'. Every Visual Basic program must be enclosed within the words 'Module' and 'End Module'. There is no rational explanation for this prerequisite. So, we accept it as the dictum. Every Module requires a name. So, we have chosen the name 'zzz'. This name has been deliberately chosen to demonstrate that the name per se, is not very significant. Any name would suffice, as long as one is present. An empty module is forbidden. Further, the error message displayed earlier clearly mandates the presence of a function or a sub-routine called Main. a.vb Module zzz Sub Main() End Sub End Module After we insert two lines within the Module, the compiler successfully compiles without any hiccups. In the directory, you will see a file called a.exe, which when executed, does not display anything. Visual Basic is a case-insensitive language. However, we still follow the Microsoft convention of writing the word Module with a capital M, even though we are at liberty to determine our own capitalization rules. After having attended to the first rule of Visual Basic, i.e. enclosing the code within the words 'Module' and 'End Module', we progress onto the second rule, which insists on the presence of a sub-routine called Main. The word 'sub' is a short form for the term sub-routine, which takes a name along with it. It is merely a collection of code. A sub-routine is created in a manner similar to the creation of a module, where we begin with the word Sub, followed by the name of the sub-routine, i.e. Main. Finally, the subroutine has to conclude with the word 'End', followed by the word 'Sub'. A 'Sub' can have a pair of open and close brackets. However, they are optional. So, on odd days we write 'Sub' with brackets in our programs, while on even days, we omit them ;-). The Visual Basic language is verbose and rather lax in its rules. Now, let us write a program that displays a string. a.vb Module zzz Sub Main() System.Console.WriteLine ("Hello") End Sub End Module

Output Hello
On compiling and executing the above program, we are greeted by the word "Hello" in the output. It has been an ancient programming tradition wherein, the first program in any programming language displays the word "Hello". The word "Hello" gets displayed on the screen because a function has been executed or called. In a programming language, a function name constitutes a word, followed by a pair of round brackets.

Thus, Main is a function, since it ends with a pair of round brackets. However, there is a subtle difference, which is: In the case of Main, we were creating a function or a sub-routine, since the line started with the word 'Sub'. In the case of System.Console.WriteLine ("Hello"), the word 'Sub' is not present. Hence, it construes that a function or subroutine is being called for execution. There is a minor distinction between a subroutine and a function, which we shall attend to later on, in the chapter. The name of our function i.e. System.WriteLine.Console, is considerably long. We need not torment ourselves about the details of how this function has been written, at this stage. We only have to be conscious of the fact that it requires some words to be inserted within double quotes, which it will display on the screen. Since we have specified the word Hello within double quotes, the console displays the word "Hello". This is the mechanism of passing data or parameters to a function. This function is one of the innumerable ones that are available in Visual Basic. We can use them on multiple occasions in our code. a.vb Module zzz Sub Main System.Console.WriteLine ("Hello") System.Console.WriteLine (100) End Sub End Module Output Hello 100 A single function is capable of embodying multiple lines of code. In the above program, we have called the function System.Console.WriteLine twice: On the first occasion, we have passed a string or a sequence of letters of the alphabet as a parameter. On the second occasion, we have passed it a number. The function dutifully prints out both the values without complaining at all. a.vb Module zzz Sub Main System.Console.WriteLine (vijay) End Sub End Module Error c:\il\a.vb(3) : error BC30451: Name 'vijay' is not declared. System.Console.WriteLine (vijay) In the WriteLine function, we have specified the word vijay, without enclosing it within inverted commas. The Visual Basic product or compiler reverts back with an error, expressing its ignorance about the name vijay. It expects it to be declared explicitly.

a.vb Module zzz Sub Main dim vijay vijay = 100 System.Console.WriteLine (vijay) End Sub End Module Output 100

To create or declare any valid name, the line must begin with the word DIM, followed by the name, thereby, informing VisualBasic.Netthat a name is being created. Thus, 'DIM vijay' signifies that the name vijay is being declared. These names are created so that they can store values in them. On the next line, we have specified a value of 100 to be stored in the name vijay. An elementary rule in all programming substituted by a name that holds the furnished with the name vijay, no error identifies the value contained in it. Since screen. a.vb Module zzz Sub Main dim vijay vijay = 100 System.Console.WriteLine vijay = 200 System.Console.WriteLine vijay = vijay + 10 System.Console.WriteLine vijay = vijay + 1 System.Console.WriteLine End Sub End Module Output 100 200 210 211 As was done in the program above, we create a name vijay and assign it a value of 100. Then, using the WriteLine function, the value is displayed. vijay is then re-assigned a new value of 200, which is also displayed. Thus, the value stored in vijay can vary. Due to this ability to hold varying values, words such as vijay, are termed as variables. On the next line, we have performed an arithmetic operation by presenting the statement vijay = vijay + 10. On encountering a line containing an 'equal to' sign =, initially all attention is riveted on the expression that is on the right side of the sign. This expression is 'vijay + 10'. So languages is that, a number or a string may be value. Therefore, when the function WriteLine is is generated. This is because, the framework first vijay holds the value of 100, it is displayed on the

(vijay) (vijay) (vijay) (vijay)

firstly, the value of vijay is evaluated to obtain a value of 200. Then, 10 is added to it, in order to obtain a result of 210. This value is now assigned to the variable on the left hand side of the 'equal to' sign, i.e. vijay, thereby updating its value. Thus, when the variable vijay is displayed, it shows the value of 210. In the next round, the value of the variable is increased by 1, thus, making the final value as 211. The concept of variables is one of the pillars on which the programming world rests. Here, a word or name holds a value, which can keep fluctuating. a.vb Module zzz Sub Main dim vijay vijay = 100 System.Console.WriteLine (vijay) vijay = "hi" System.Console.WriteLine (vijay) End Sub End Module Output 100 hi In this example, the variable vijay is first assigned a numeric value 100. Then, it is assigned a string value of "hi". Nobody complains and both values get displayed. Thus, we have the license to change the data type of the value that the variable can hold. a.vb Module zzz Sub Main dim vijay as integer vijay = 100 System.Console.WriteLine (vijay) vijay = "hi" System.Console.WriteLine (vijay) End Sub End Module Output 100
Unhandled Exception: System.InvalidCastException: Cast from string "hi" to type 'Integer' is not valid. ---> System.FormatException: Input string was not in a correct format. at Microsoft.VisualBasic.CompilerServices.DoubleType.Parse(String Value, NumberFormatInfo NumberFormat) at Microsoft.VisualBasic.CompilerServices.IntegerType.FromString(String Value) --- End of inner exception stack trace --at Microsoft.VisualBasic.CompilerServices.IntegerType.FromString(String Value) at zzz.Main()

The previous program does not demonstrate the conventional technique of programming, because a variable must essentially represent only a single type during its lifetime. To maintain absolute consistency, the data type is specified while creating the variable. This is achieved by adding the word 'as' after the DIM variable, followed by a predefined data type. vijay is assigned the data type of integer, which implies that the variable vijay shall store only numbers or integers. After displaying the number that it contains, the variable vijay is then initialized to a string value of "hi". The earlier program had not protested under similar circumstances. However, now we come across a mammoth dialog box displaying an error message. When we click on No, we observe the above error on the console. This error or exception enucleates the fact that, we are not empowered to specify a string value for a variable that has been declared to be of type integer. Henceforth, we shall declare all our variables with a data type. a.vb Module zzz Sub Main dim i,j as integer i = 10 System.Console.WriteLine ("{0} {1}", i, j) End Sub End Module Output 10 0 In a single stroke, we have the ability to create as many variables as we wish, separating each one of them with a comma. The above example has two integer variables named i and j, which have been declared together. The variable i is assigned a value of 10, while j is not initialized at all. In the same manner that was used to create two variables simultaneously, we now wish to print their values too in a single stroke. To accomplish this, the WriteLine function has been modified and assigned a string that has the numbers 0 and 1 enclosed within curly braces. This string parameter is followed by the two variables i and j, separated by commas. They are extra parameters. The WriteLine function replaces the first curly brace of 0, with the value of the first parameter after the string i.e. i, and the second curly braces of 1 with the second parameter after the string, i.e. j. Since the value of the variable i is 10, and the value of the variable j is 0, the output that is displayed is 10 0. Thus, not only have we learnt how to print multiple variables using a single WriteLine function, but have also become wiser by the fact that, if a variable is not assigned a value, it obtains a default value of 0. a.vb Module zzz Sub Main dim b as boolean dim i as integer dim j as string j = "hi" i = 10 b = true

System.Console.WriteLine ("{0} {1} {2} {3}" , i > 20 , i < 20 , b , j = "hi") End Sub End Module Output False True True True A data type represents a specific type of data. In the above example, we have created three types of variables: i is of type integer j is of type string b is of type Boolean. A Boolean type can store only one of the two values, true or false. The variable i of type integer can hold any valid number. It is assigned the value of 10. The variable j, of type string, must have its value enclosed within double inverted commas. It is assigned a value of "hi". The boolean variable b is initialized to a value of true. In the WriteLine function following the string, we first display the expression i > 20, instead of the variables. Doing so, indirectly poses the question "Is the variable i greater than 20?" The result can either be true or false. Since the value of the variable i is 10, which is less than 20, the value of False is displayed. The second expression determines whether the value of i is less than 20 or otherwise. Since this is affirmative, the value of True is displayed on the screen. The third parameter to the WriteLine function simply displays the value of the boolean variable b. The value of the boolean variable is not altered from what it was initialized to. Hence, the output is displayed as True. The last check performed is, whether the value of the string j is equal to the string value "hi" or not. Since they both are the same, the resultant value of True is displayed. Thus, all the above expressions result in a boolean value of either true or false. a.vb Module zzz Sub Main dim i as integer i = 10 if i > 50 then System.Console.WriteLine ("Condition True") End if if i > 5 then System.Console.WriteLine ("Second Condition True") End if End Sub End Module Output Second Condition True

The programs that we have presented so far are absolutely straightforward, since every line of code that is entered, gets called sequentially. We desire to execute code based on certain circumstances. The above program is the perfect prescription for this. We have created an integer i with a value of 10. Then, we encounter an 'if' statement. An 'if' statement is always followed by a condition or an expression, and the line ends with a 'then'. In the first case, a check is performed to determine whether the value of the variable i is larger than 50 or not. Since the answer is False, all the lines of code leading up to the 'End If', are ignored. Thus, the first WriteLine function with the Condition True, does not get executed at all. The condition with the second 'if' statement, verifies whether the value of i is greater than 5 or not. Since it is, all the code between the 'if' and the 'end if' is executed. Thus, an 'if' statement is used to make decisions, i.e. to intelligently execute specific code, depending upon whether some variables have certain values or not. In this manner, we can effortlessly write intelligent and dynamic programs. a.vb Module zzz Sub Main dim i as integer i = 10 if i > 50 then System.Console.WriteLine ("Condition True") else System.Console.WriteLine ("Condition False") End if if i > 5 then System.Console.WriteLine ("Second Condition True") End if End Sub End Module Output Condition False Second Condition True In the above program, the 'if' statement now has the 'else' clause added to it. In the earlier program, when the result of the 'if' statement was false, no code was executed. Now, since the 'else' clause has been added, whenever the 'if' statement is false, the statements within the 'else' block are executed. So, all code from the 'else' upto the 'end if', is executed. When the 'if' condition results in True, the statements contained within the 'if' upto the 'else', are executed. The advantage of using the 'else' clause is that, some code finally gets executed. However, the 'else' clause is optional. Subroutines a.vb Module zzz Sub Main abc

End Sub End Module Error c:\il\a.vb(3) : error BC30451: Name 'abc' is not declared. By introducing the name abc, we have attempted to call a subroutine or a function by that name. Like before, an error is generated, since abc has not been declared. Thus, as in the case of variables, we have to declare or create the subroutine or function before calling our own code. a.vb Module zzz Sub Main abc End Sub sub abc System.Console.WriteLine("in abc") end sub End Module Output in abc At the very outset, we had created a subroutine called Main, by using Sub. Harnessing the same mechanism, we now create another subroutine called abc. The only difference between the two sub-routines is that the code in Sub Main is called when the .exe file is executed, whereas, the code in the other subroutines has to be called explicitly. To execute code in a subroutine, just the name of the subroutine has to be specified on a blank line. Hence, we have merely specified the name abc. This action calls the code in the subroutine, thereby resulting in the WriteLine function being called, with the string 'in abc'. This sounds too easy to be true! a.vb Module zzz Sub Main abc pqr End Sub sub abc System.Console.WriteLine("in abc") pqr() pqr end sub sub pqr System.Console.WriteLine("in pqr") end sub End Module Output in abc in pqr in pqr

in pqr We can create as many subroutines or subs as we like in a single module. The above program displays two subroutines, both of which are called from the Main block. Furthermore, the pqr subroutine is called twice from the abc subroutine. Thus, we enjoy the privilege of calling code contained in any other subroutines, as many times as we desire. You would notice that at one stage we had called the pqr subroutine, using the open and close brackets. The brackets are optional. So, their presence or the lack of it, does not interfere much with the execution of the code. a.vb Module zzz Sub Main abc("Hi") End Sub sub abc() System.Console.WriteLine("hell") end sub End Module c:\il\a.vb(3) : error BC30057: Too many arguments to 'Public Sub abc()'. In the above example, an error is generated, since we are passing the string parameter "Hi" to the sub abc; whereas, the sub abc has not been declared to accept any parameters. So, let us rectify this situation in the subsequent example. a.vb Module zzz Sub Main abc("Hi") End Sub sub abc(s as string) System.Console.WriteLine(s) end sub End Module Output Hi The above example demonstrates the correct way of creating a subroutine. The string "hi" is passed as the value for the variable 's' in the sub abc. The variable 's' is termed as a parameter. It is supplied to the WriteLine function for display purposes. Subroutines that accept parameters are very practical and efficacious, since they infuse a lot of flexibility and generality into the program. a.vb Module zzz Sub Main Dim s,t,u as string s = "hi" t = "bye" u = "No" abc(s,t,u) System.Console.WriteLine("{0} {1} {2}",s,t,u) End Sub

sub abc(s0 as string , byval s1 as string, byref t1 as string) System.Console.WriteLine("{0} {1} {2}",s0,s1,t1) s0 = "good" s1 = "bad" t1 = "ugly" end sub End Module Output hi bye No hi bye ugly In the above example, there are three string variables viz. s, t and u. They are initialized to "Hi", "Bye" and "No", respectively. These three variables are then furnished as parameters to the subroutine abc. In the Sub, the values passed by the three variables, are stored in the parameters s0, s1 and t1. We will explore the other parameter details in a short while. Thereafter, the three values are displayed using the WriteLine function. Then, the values of the parameters s0, s1 and t1 are modified to some other values. Once the subroutine abc ends, the control moves on to the next line in the Main block. Here, we again use the WriteLine function to display the values of the variables s, t and u. To our utter astonishment, we discover that the value of the variable 'u' is different from what it had been initialized to. It displays the new value that has been assigned to it in the abc subroutine. However, s and t retain their old values. In sub abc, we have changed the values of the parameters, and not the original variables. Notwithstanding this, the value contained in the variable 'u' within the main subroutine, changes. This is because of the fact that, we have affixed the word 'byref' before the name of the parameter. This word signifies that if the parameter t1 changes in the sub abc, the original variable in the calling Sub would also change correspondingly. By using the word 'byval', any changes made to the value of the variable in the subroutine, would not percolate down to the original variable. The default is 'byval', and since it has not been mentioned for the first parameter, the effect is that of byval. Thus, it is the sub that decides on whether to reflect the changes made, onto the original variable that is passed as a parameter. a.vb Module zzz Sub Main Dim s as string s = "hi" abc() End Sub sub abc() s = "No" end sub End Module Error c:\il\a.vb(8) : error BC30451: Name 's' is not declared.

We did not enlighten you earlier about a very essential feature of Sub. However, this seems to be an opportune time to divulge the fact that, a Sub is an independent and a self-contained entity. The variable 's' created in the sub main, is not discernible in the sub abc. Hence, the compiler generates the above error. a.vb Module zzz Sub Main Dim s as integer s = abc(10,20) System.Console.WriteLine(s) End Sub Function abc(i as integer , j as integer) as integer abc = i + j end Function End Module Output 30 Your reaction to this book could range from being extremely positive to being outright negative and unimpressed. This would depend upon how well you relate to our style. It has always been our endeavour to explain only a single concept at a time. This could get exasperating for a large number of people. The above example highlights the difference between a sub and a function. They are almost identical, but for one variation, i.e. a function can return a value, whereas, a Sub cannot. In many situations, returning values is very important because functions normally perform certain tasks and return the result of their operation. The above function abc accepts two integers parameters and returns their sum. Creating functions is a child's play, since it entails replacement of the word 'Sub' with the word 'Function' and the words 'End Sub' with the words 'End Function'. The words 'as Integer' signify that the function will return an integer when it is called. To return a value in a function, the name of the function has to be initialized to the specific value. Thus, writing abc=100 will return 100. In our case, we are adding up the two parameters 10 and 20, and initializing the function name abc with the sum of 30. Thus, the variable s in the sub main will now have a value of 30, which is the return value of the Function. a.vb Module zzz Sub Main Dim s as integer s = abc(10,20) abc(100,300) System.Console.WriteLine(s) End Sub Function abc(i as integer , j as integer) as integer abc = 300 abc = i + j end Function End Module

Output 30 You may set the return value as many times as you like. No one would whine. The last value to be returned will be the one that is finally used. Thus, the return value of 300 is overridden by the last value to be returned, i.e. 30. Even though it is the job of a function to return a value, we can avoid storing the return value in a variable. Thus, in the second round, when the function abc is called, we do not save its return value in a variable. However, nobody makes a fuss about it. As has been oft repeated by us, VisualBasic.Netis a very forgiving and flexible language, and that is precisely why we love it as much as we do!

Das könnte Ihnen auch gefallen