http://r4r.co.in/c C# Tutorials
1. Introduction 2. Net Framework Architecture 3. Data types in C# 4. C# and other Programm Programming ing Languages 5. Fundamentals of C# 6. Operators, types and variables in C# 7. Control Statements 8. Arrays, Indexer and Collections 9. Inheritance and Polymorphism 10. Properties 11. Attributes 12. Structs 13. Delegates and Events 14. Exception Handling 15. File Handling in C# 16. Threading 17. Introduction to Visual Studio 18. Introducing Windows Forms 19. Button Control 20. Label and Link Label 21. TextBox control 22. Radio Button and CheckBox Controls 23. GroupBox Control 24. Rich TextBox Control 25. ListBox Controls 26. ComboBox Controls 27. Listview Control 28. StatusBar Control 29. Tabcontrol Control 30. NotifyIcon Control 31. Masked Textbox 32. Window Media Player 33. Dialog Controls 34. Printing Controls 35. Data Controls 36. Error Provider Control 37. Help Provider 38. Reporting Control 39. Flow Layout Panel 40. Table Layout Panel
41. Panel Control 42. Split Container Control 43. DateTimePicke DateTimePickerr and Month Calendar 44. NumericUpDow NumericUpDown n Control 45. ProgressBar and Timer Control 46. ToolTip Control 47. TreeView Control 48. Menus and ToolBar Controls 49. Background Worker Control 50. Creating Slice Chart in windows using C# 51. Socket 52. Creating Bar Chart in windows using C# 53. dll 54. GDI(Graphics Design Interface) 55. Access IP Address of LAN Connected Computers 56. IP Address of Websites in C# application 57. Creating Line Chart in windows using C# 58. Pie chart 59. Creating Line Chart in windows using C# 60. Synchronization in C# 61. Creating Word document using C# 62. How to Add Manually CheckBox in C# 63. How to Change The Color of Specific Word in
Rich textbox using
C# 64. Reading/Writing/Ap Reading/Writing/Appending pending a Text File, Using c# 65. How to Find Max Value of X, Y ,Z From Text file Using C# 66. How to Take Printout of RichtextBox 67. Multiple Colored Texts in RichTextBox using C# 68. How to Create Stopwatch in C# 69. Add Header and Footer to Word Document Using C# 70. How to Add Table in Word Document using C# 71. Add rows to table in MS Word document using C# 72. How to Add image in Word Document using C# 73. Storing Database Connection Strings in App.Config 74. Blink Label Color In Every Half Of Second Using C# 75. How to Draw Chec CheckBoa kBoard rd in C#: 76. Change a label's forecolor on mouseovers in C# 77. Draw a curve on form using Graphics Graphi cs class in C #.net. 78. Draw a polygon on form using Graphics class C #.net 79. Drawing Lines in C# 80. Drawing Text with C#
81. Export gridview to pdf in c# 82. How to Draw Ellipse using mouse dragging in C# 83. Difference between Array and ArrayList 84. How to Rotate Image in Picture Box Using C# 85. Calculating Duration Between Two Dates in Years,
Months and
Days 86. Advantage of Remoting,Advantage over Web Services?,Advantage over COM/DCOM? 87. Caching in ASP.Net 88. How to Save Data in XML File 89. How to use xml 90. Remoting in asp 91. Transaction in asp What is C#? C# is intended to be a simple, modern, general-purpose, object-oriented programming language. Its development team is led by Anders Hejlsberg. The most recent version is C# 4.0, which was released on April 12, 2010. C# (pronounced "see sharp") is a multiparadigm programming language encompassing imperative, declarative, functional, generic, object-oriented (class-based), and component-oriented programming disciplines. It was developed by Microsoft within the .NET initiative and later approved as a standard by Ecma (ECMA-334) and ISO (ISO/IEC 23270). C# is one of the programming languages designed for the Common Language Infrastructure.
Features of C# Some notable distinguishing features of C# are: •
•
•
•
•
There are no global variables or functions. All methods and members must be declared within classes. Static members of public classes can substitute for global variables and functions. Managed memory cannot be explicitly freed instead, it is automatically garbage collected. Garbage collection addresses the problem of memory leaks by freeing the programmer of responsibility for releasing memory which is no longer needed. In addition to the try...catch construct t o handle exceptions, C# has a try...finally construct to guarantee execution of the code in the finally block. Multiple inheritance is not supported supported by C#, although although a class can implement any number of interfaces.
C# and .Net Framework Microsoft announced C# in July 2000, its unveiling was part of a much larger event the announcement of the .NET Framework. The .NET Framework is, in essence, a new development framework that provides a fresh application programming interface (API) to
the services and APIs of classic Windows operating systems (especially the Windows 2000 family), while bringing together a number of disparate technologies that emerged from Microsoft during the late 1990s. Among the latter are COM+ component services, the ASP web development framework, a commitment to XML and object- oriented design, support for new web services protocols such as SOAP, WSDL, and UDDI, and a focus on the Internet Information Services.
What is CLR? CLR (Common Language Runtime) is the most important component of .Net Framework. It manages and executes code written in .Net Languages, CLR activates objects and perform security checks. The CLR allows programmers to ignore many details of the specific CPU that will execute the program. It also provides other important services, including the following: • • • • •
Memory management Thread management Exception handling Garbage collection Security Central to the .NET .NET Framework is its runtime execution execution environment, environment, known as the Common Language
Runtime (CLR) or the .NET runtime. r untime. Code running under the control of the CLR is often termed as managed code.
What is CTS? In .NET Framework, the Common Type System (CTS) is a standard that specifies how Type definitions and specific values of Types are represented in computer memory. It is intended to allow programs written in different programming languages languages to easily share information. Functions of the Common Common Type System:•
•
•
•
CTS establishes a framework that helps enable cross-language integration, type safety, and high performance code execution. CTS provides an object-oriented model that supports the complete implementation of many programming languages. CTS also defines rules that that languages must must follow, which helps ensure that objects written in different languages can interact with each other. Languages supported by .NET can implement all or some common data types.
Type categories the common type system supports t wo general categories of types:
Value types:
Value types directly contain their data, and instances of value types are either allocated on the stack or allocated inline in a structure. Value types can be built-in (implemented by the runtime), user-defined, or enumerations.
Reference types:
Reference types store a reference to the value's memory address, and are allocated on the heap. Reference types can be self-describing types, pointer types, or interface types. The type of a reference type can be determined from values of self-
describing types. Self-describing types are further split into arrays and class types. The class types are user-defined classes, boxed value types, and delegates.
What is CLS? The Common Language Specification (CLS) is a part of the standardized specification of the .NET Framework originally defined by Microsoft, and later standardized by the European Computer Manufacturers Association (ECMA). A key feature of .NET .NET Framework is that applications written in different languages can interoperate with one another, taking advantage of inheritance, polymorphism, exceptions and other features. CLS provides, set of specification to be adhered by new language writer/compiler writer for .Net Framework to ensure interoperability. because .net supports many languages.For example Asp.Net application written written in C#.Net language. Now we we can refer any other other DLL which has been written in any other language supported by .Net Frame Work.
Net Frameworks Architecture
.Net is not an Operating System. It is a IDE. It provides some functionality for the programmers to build their solution solution in the most constructive and intellegent intellegent way ever. Just to tell you the truth, most of the codes in .Net environment resembles with the JAVA coding as if some people coming from Java would find it as to their native language. .NET is a Framework that loads into your operating system, which you need not to load in the later versions of windows like Windows 2003 server or Just a new release of Windows Vista. As it is going to be added as a component in the next generation of windows.
Now, What is the .Net all about? Well, Its a framework that t hat supports Common Language Runtime (CLR). As the name suggests, Common Language Runtime will be something that will run a native code for all the programming languages provided within the Architecture. Another feature of .net is language independence, to tell you about language Independence, .Net is not at all efficient in that. Just Microsoft built their own version of languages like C+ +, J# (for Java), C#, VB etc that can communicate between each other. After all J#, even if they resembles with JAVA is not purely Java.. Thus, the word may look to you somewhat fake. Now what is the most prospective part of .NET? Now, with the growing Internet, ASP. NET may be the most important part of .NET technology. Well, ASP. NET has a new technology where the controls reside server side. You don't bother to use traditional client side controls. In .NET technology as there is a provision of runtime building of machine codes, a web server can directly compile and transmit codes to the browser during runtime. This is , I think the most approved and widely accepted part of .NET. NEW things of .NET? well, during the last two years , Microsoft is constantly changing the .NET technology, that may not be good for a settled programmer. Well, first of all, in .NET 2003 Microsoft changed some features and al so adds some new things. Well, new things are good, but changing the existing in such a quick succession is not at all good from programmers point of view. Again, in 2005, Microsoft publishes the new release of VISUAL STUDIO.NET 8 . This is a completely new environment. It have new releases of controls, the IDE is also different. That's not what we all wanted as a programmer. What do you say? Now, Microsoft is also increasing its scope.. One of the most important feature that is just now introduced is AJAX. Well, the name is what can be said as Asynchronous Java Script with XML.
.Net Frameworks Architecture
C# DataTypes Data Types means what type of data a variable can hold . C# is a strongly typed language, therefore every variable and object must have a declared type. The C# type system contains three Type categories. • • •
Value Types Reference Types Pointer Types
In C# it is possible to convert a value of one type into a value of another type . The operation of Converting a Value Type to a Reference Type is called Boxing and the reverse operation is called Unboxing . Ex.
int month; int : is the data type month: is the variable name
int int can store signed 32 bit integer values in the range of -2,147,483,648 to +2,147,483,647 C# Runtime type : System.Int32 C# declaration : int month;
C# Initialization : month = 10; C# default initialization value : 0
decimal Decimal is of a 128-bit data type.The approximate range and precision for the decimal type are -1.0 X 10-28 to 7.9 X 1028 C# Runtime type : System.Decimal C# declaration : decimal val; C# Initialization : val = 0.12; C# default initialization value : 0.0M
string Represents a string of Unicode characters. string variables are stored any number of alphabetic,numerical, and special characters . C# Runtime type : System.String C# declaration : string str; C# Initialization : str = ".Net Environment";
bool Bool is used to declare variables to store the Boolean values, true and false. In C# , there is no conversion between the bool type and other types. C# Runtime type : System.Boolean C# declaration : bool flag; C# Initialization : flag = true; C# default initialization value : false The following list shows the list of data types available in C# and their corresponding class/struct in .NET class library. C# Dat Data a type type
Mapp Mapped ed to to .NET .NET clas class/ s/st stru ruct ct
sbyte
System.SByte
byte
System.Byte
char
System.Char
float
System.Single
decimal
System.Decimal
double
System.Double
ushort
System.UInt16
short
System.Int16
uint
System.UInt32
int
System.Int32
ulong
System.UInt64
long
System.Int64
bool
System.Boolean
string
System.String
object
System.Object
Boxing: Converting value types to reference types is also known as boxing. As can be seen in the example below, it is not necessary to tell the compiler an Int32 is boxed to an object, because it takes care of this itself. e.g.-
Int32 a = 10 10;; object count = a ; // ; // Implicit boxing Console.WriteLine( Console .WriteLine("The "The Object count = {0}",count); {0}" ,count); // // prints out 10 //However, an Int32 can always be explicitly boxed like this: Int32 a = 10 10;; object count = (object (object)) a; // a; // Explicit boxing Console.WriteLine( Console .WriteLine("The "The object count = {0}",count); {0}" ,count); // // prints out 10
Unboxing: The following example intends to show how to unbox a reference type back to a Unboxing: value type. First an Int32 is boxed to an object, and then it is unboxed again. Note that unboxing requires explicit cast. Ex.
Int32 a = 5; object count = a; // a; // Implicit Boxing a = (int ( int)count; )count; // // Explicit Unboxing
Type Conversions Conversion is based on type compatibility and data compatibility. •
Implicit Conversion: Implicit Conversion make conversion for us without asking.
In implicit conversion the compiler will
char -> int -> float is an example of data compatibility.
using System System;; class Program { static void Main(string Main(string[] [] args) { int x =10000 =10000;; int y =20000 =20000;; long total; // In this the int values are implicitly converted to long data type; //you need not to tell compiler to do the conversion, it automatically automatically does. total = x + y; Console.WriteLine( Console .WriteLine("Total "Total is : " + total); Console.ReadLine(); Console .ReadLine(); }
}
•
Explicit Conversion: In explicit conversion we specifically ask the compiler to convert the value value into another another data type. CLR checks for data data compatibility at runtime.
using System System;; class Program { static void Main(string Main(string[] [] args) { int x = 65 65;; char value; value = (char (char)x; )x; // In this the int values are explicitly converted to char data type; //you have to tell compiler to do the conversion, it uses casting. Console.WriteLine( Console .WriteLine("Value "Value is: " + value); Console.ReadLine(); Console .ReadLine(); } }
Microsoft .NET provides three ways of type conversion: •
Parsing Parsing is used to convert string type data to primitive value type. For this we use parse methods with value types.
using System System;; class Program { static void Main(string Main(string[] [] args) { //using parsing int number; float weight; Console.Write( Console .Write("Enter "Enter any number : "); " ); number = int int.Parse( .Parse(Console Console.ReadLine()); .ReadLine()); Console.Write( Console .Write("Enter "Enter your weight : "); " ); weight = float float.Parse( .Parse(Console Console.ReadLine()); .ReadLine()); Console.WriteLine( Console .WriteLine("You "You have entered : " + number); Console.WriteLine( Console .WriteLine("You "You weight is : " + weight); Console.ReadLine(); Console .ReadLine();
} }
•
Convert Class Convert class contains different static methods like ToInt32(), ToInt16(), ToString(), ToDateTime() etc used in type conversion.
using System System;; class Program { static void Main(string Main(string[] [] args) { // example of using convert class string num = "23" "23";; int number = Convert Convert.ToInt32(num); .ToInt32(num); int age = 24 24;; string vote = Convert Convert.ToString(age); .ToString(age); Console.WriteLine( Console .WriteLine("Your "Your number is : " + number); Console.WriteLine( Console .WriteLine("Your "Your voting age is : " + age); Console.ReadLine(); Console .ReadLine(); } }
•
Explicit Cast Operator () It can used with any type having type compatibility and data type compatibility.
using System System;; class Program { static void Main(string Main(string[] [] args) { int num1, num2; float avg; num1 = 10 10;; num2 = 21 21;; avg = (float (float)(num1 )(num1 + num2) / 2; Console.WriteLine( Console .WriteLine("average "average is : " + avg); Console.ReadLine(); Console .ReadLine(); } }
Similarity and difference with C/C++
•
•
•
C# is directly related to C and C++, C++ is a superset of C. C and C++ shares several syntax, library and functionality. In addition structures, unions, arrays, strings and pointers are most important and similar functionality for both languages. C# inherits most of its operators, keywords, and statements directly from C++. Enums are clearly a meaningful concept in C++. Finally I can clearly say that C# is the first component-oriented language in the C/C++ family. C# constructors are verisimilar with C++ constructors. Like C++, methods are nonvirtual by default, but can be marked as virtual.
There is also some difference between C# and C++, C# supports multiple inheritance of interfaces, but not of classes. Another difference is destructors, their syntax is same with C++ but actually they are very different.
Difference between C# and VB 1. C# allows 'unsafe' 'unsafe' code, code, or pointer pointer manipulatio manipulation. n. VB allows methods methods with option optional al parameters. 2. C# allows allows assignments assignments embedded embedded in expres expressions sions (e.g., (e.g., if ((x = y.Value) y.Value) == 2)).VB 2)).VB allows types within interfaces. 3. C# has anonymo anonymous us methods.VB methods.VB has the very very flexible flexible Select construct construct (much (much more flexible than the C# switch). 4. C# has the usefu usefull conditional conditional ternary ternary operator operator (?:). The The VB If function function is not not a good substitute since the arguments must all be evaluated. VB has the When filter for catch block headers (no equivalent exists in C#).
Difference between C# and Java Features of C# not present in Java 1. C# prov provide ides s integr integrati ation on with with COM. COM. 2. C# has "Explicit "Explicit Member Member Implement Implementation" ation" which which allows allows a class to specifica specifically lly implement methods of an interface, separate from its own class methods. 3. C# has has the abili ability ty to alias alias name namespa spaces. ces. 4. C# has support support for for output output parameters, parameters, aiding aiding in the return return of multipl multiple e values, values, a feature shared by C++ and SQL. 5. C# impleme implements nts properties properties as part of the the language language syntax syntax.. 6. C# allows allows switch switch statem statements ents to operate operate on strings. strings.
7. Nam Namesp espac ace e in C# C# 8. Namespaces Namespaces group group related related classes classes and types, types, and they they define define categories categories in which which we can include any new class that provides related functionality.
namespace MyCompany.r4r { class MyClass { // some code here } }
namespace MyCompany.r4r { class MyClass1 { // some code here } }
9. Clas Classes ses and Obj Object ect in C# 10. Defining Classes: To define a new type or class, first declare it, and then define its methods and fields. Declare a class using the class keyword. The complete syntax is as follows: [attributes] [access-modifiers] class identifier [:base-class] [:base-class] { class-body } 11. For Example. Example.
public class Test { public static int Main( ) { Console.Writeline( Console .Writeline("This "This is Class"); Class"); } }
12. Defining Object: A distinction is drawn between value types and reference types. The primitive C# types (int, char, etc.) are value types, and are created on the stack. Objects, however, are reference types, and are created on the heap, using the keyword new, new, as in the following: Test t = new Test();
13. t does not actually contain the value for the test class object; it contains the address of that (unnamed) object that is created on the heap. t itself is just a reference to that object.
14. How to create a program in C#? 15. Step 1: Start notepad from Start -> Program Files -> Accessories -> Notepad so that you can write the HelloWorld program. The program you write in C# is also called as source code. 16. Step 2: Write the HelloWorld program, you can e ither type the program shown below into notepad or just copy-paste it from here-
public class Helloworld {
public static void Main() { System..Console System Console.WriteLine( .WriteLine("you "you are welcome in world of C#"); C#" ); } }
Step 3: Once you have finished typing your program you should Save the source code file. In fact after making any changes to your source source code, you should always save the the file. To save the file for the first time in notepad click on File menu -> Save As. In the Save As dialog select the directory from the Save In dropdown where you want to save your files, I generally save my files to C:\cs harp, and then in the File name textbox, enter the file name as HelloWorld.cs (although you can provide any name you want but it should have an extension.cs). and click Save. Once you have saved the source code, and if you make any further modifications, in notepad use the Ctrl+S keyboard short-cut to save your source code file. Step 4: Since you have finished writing the source code its time to compile it. Since we are using a command-line compiler that ships with the .NET SDK, start the command prompt from Start -> Program Files -> Accessories -> Command Prompt. Or go to Start -> Run, type cmd and press enter. Now from the command prompt navigate to the directory where you have stored the source code file by issuing the following DOS commands.cd\ -To navigate to the root of the derived csharp - To navigate to the csharp directory. Once you are in the csharp directory where you saved the source code file earlier, its time to run the C# Compiler csc.exe. Issue the following command to compile our HelloWorld.cs program:csc HelloWorld.cs Step 5: If the compilation of the source code was successful then a new executable (Exe) file by the name HelloWorld.exe will be created in the directory you compiled the source code. To execute the program simply type the name of the executable file at the command prompt. Points to Remember 1. 2. 3. 4.
C# code code can be written written in in any text text editor editor like like notepad. notepad. C# Source Source Code Code files files are saved saved with with the extension extension.cs. .cs. C# is a case-sensiti case-sensitive ve language language so you have have to be carefu carefull while typing. typing. C# runs on the the .NET .NET Platform, Platform, hence you you need to install install the .NET .NET SDK in order order to compile C# programs. 5. The C# compiler compiler is contained contained within within the the file csc.exe, csc.exe, which which generally generally resides resides in the C:\windows\Microsoft. NET\Framework\v1.0.4322 directory.
6. Operato Operators, rs, types types and variable variables s in C#
7. Variables: A variable is a storage location with a type. Variables can have values assigned to them, and those values can be changed programmatically. A constant is a variable whose value cannot be changed. 8. Types: Like C++ and Java, C# divides types into two sets: intrinsic Built-in types that the language offers and user-defined types that the programmer defines. C# also divides the set of types into two other categories: value types and reference types. The principal difference between value and reference types is the manner in which their values are stored in memory. C# is a "Strongly Typed" language. Thus all operations on variables are performed with consideration of what the variable's "Type" is. There are rules that define what operations are legal in order to maintain the integrity of the data you put in a variable. 9. The Boolean Type: Boolean types are declared using the keyword, bool. They have two values: true or false. In other languages, such as C and C++, boolean conditions can be satisfied where 0 means false and anything else means tr ue. However, in C# the only values that satisfy a boolean condition is true and false, which are official keywords.
using System System;; class Booleans { public static void Main() { bool content = true true;; bool noContent = false false;; Console.WriteLine( Console .WriteLine("{0} "{0} C# programming language content.", content." , content); Console.WriteLine( Console .WriteLine("This "This is second statement {0}.", {0}." , noContent); } }
10. Integral Types: In C#, an integral is a category of types. For anyone confused because the word Integral sounds l ike a mathematical term, from the perspective of C# programming, these are actually defined as Integral types in the C# programming language specification. They are whole numbers, either signed or unsigned, and the char type. The char type is a Unicode character, as defined by the Unicode Standard. 11. Floating Point and Decimal Types: A C# floating point type is either a float or double. They are used any time you need to represent a real number. Decimal types should be used when representing financial or money values. 12. The string Type: Type: A string is a sequence of text characters. You typically create a string with a string literal, enclosed in quotes: "This is an example of a string." You've seen strings being used in Lesson 1, where we used the Console.WriteLine method to send output to the console. Arr ay, which can be thought of as a 13. The Array Type: Another data type is the Array, container that has a list of storage locations for a specified type. When declaring an Array, specify the type, name, dimensions, and size.
using System System;; class NewArray { public static void Main() { int[] int [] myInts = { 5, 10 10,, 15 }; bool[][] bool [][] myBools = new bool[ bool [2][]; myBools[0 myBools[0] = new bool[ bool [2]; myBools[1 myBools[1] = new bool[ bool [1]; double[,] double [,] myDoubles = new double[ double [2, 2]; string[] string [] myStrings = new string[ string[3]; Console.WriteLine("myInts[0]: Console.WriteLine( "myInts[0]: {0}, myInts[1]: {1}, myInts[2]: {2}", {2}" , myInts[0 myInts[ 0], myInts[1 myInts[ 1], myInts[2 myInts[2]); myBools[0 myBools[0][0 ][0] = true true;; myBools[0 myBools[0][1 ][1] = false false;; myBools[1 myBools[1][0 ][0] = true true;; Console.WriteLine( Console .WriteLine("myBools[0][0]: "myBools[0][0]: {0}, myBools[1][0]: {1}", {1}" , myBools[0 myBools[ 0][0 ][0], myBools[1 myBools[ 1][0 ][0]); myDoubles[0 myDoubles[0, 0] = 4.245 245;; myDoubles[0 myDoubles[0, 1] = 6.355 355;; myDoubles[1 myDoubles[1, 1] = 8.415 415;; myDoubles[1 myDoubles[1, 0] = 56 56..1148917 1148917;; Console.WriteLine( Console .WriteLine("myDoubles[0, "myDoubles[0, 0]: {0}, myDoubles[1, 0]: {1}", {1}" , myDoubles[0 myDoubles[ 0, 0], myDoubles[1 myDoubles[1, 0]); myStrings[0 myStrings[0] = "An" "An";; myStrings[1 myStrings[1] = "App" "App";; myStrings[2 myStrings[2] = "Cattt" "Cattt";; Console.WriteLine( Console .WriteLine("myStrings[0]: "myStrings[0]: {0}, myStrings[1]: {1}, myStrings[2]: {2}", {2}" , myStrings[0 myStrings[0], myStrings[1 myStrings[1], myStrings[2 myStrings[ 2]); } }
The if Statement if statement is used to take different paths of logic, logic, depending on the conditions. conditions.
using System; System; using System System..Windows Windows..Forms Forms;;
class iftest { public static void Main() { if (totalMarks if (totalMarks >= 80 80)) { MessageBox.Show( MessageBox .Show("Got "Got Higher First Class "); "); } else if if (totalMarks (totalMarks >= 60 60)) { MessageBox.Show( MessageBox .Show("Got "Got First Class "); "); } else if (totalMarks if (totalMarks >= 40 40)) { MessageBox.Show( MessageBox .Show("Just "Just pass only"); only" ); } else { MessageBox.Show( MessageBox .Show("Failed" "Failed"); ); } } }
The switch Statement Another form of selection statement is t he switch statement, which executes a set of logic depending on the value of a given parameter. The types of the values a switch statement operates on can be booleans, enums, integral types, and strings.
using System System;; class SwitchTest { public static void Main() { Console.WriteLine( Console .WriteLine("milk "milk bottel size: 1=Small 2=Medium 3=Large"); 3=Large" ); Console.Write( Console .Write("Please "Please enter your selection: "); "); string s = Console Console.ReadLine(); .ReadLine(); int n = int int.Parse(s); .Parse(s); int price = 0; switch(n) switch (n) { case 1: price += 25 25;; break;; break case 2:
price += 25 25;; goto case 1; case 3: price += 50 50;; goto case 1; default:: default Console.WriteLine( Console .WriteLine("Invalid "Invalid selection. Please select 1, 2, or 3."); 3." ); break;; break } if (price if (price != 0) Console.WriteLine( Console .WriteLine("Please "Please insert {0} cents.", cents.", price); Console.WriteLine( Console .WriteLine("Thank "Thank you for your business."); business." ); } }
The while Loop While loop is used to check a condition and then continues to execute a block of code a s long as the condition evaluates to a boolean value of true. Syntax:while (
) { } When the boolean expression evaluates to false, the while loop statements are skipped and execution begins after the closing brace of that block of code.
using System System;; class whiletest { static void Main() { // // Continue in while loop until index is equal to ten. // int i = 0; while (i < 10 10)) { Console.Write( Console .Write("While "While statement "); "); // // Write the index to the screen. // Console.WriteLine(i); Console .WriteLine(i); // // Iterate the variable. //
i++; } } }
The do Loop A do loop is similar to the while loop, except that it checks its condition at the end of the loop. This means that the do loop is guaranteed to execute at least one time.
using System System;; class DoWhileLoopDemo { public static void Main() { int i = 0; // Initialize counter variable do { if ((i if ((i % 2) == 0) { Console.WriteLine(i); Console .WriteLine(i); } i++; //Increment the counter } while (i <= Limit); // Limit); // Condition check } }
The for Loop It works like a while loop, except that the syntax of the for loop includes initialization and condition modification. for loops are appropriate when you know exactly how many times you want to perform the statements within the loop. The contents within the for loop parentheses hold three sections separated by semicolons (; ; ) { }.
using System System;; class ForLoop { public static void Main() { for (int i=0 i=0; i < 20 20;; i++) { if (i if (i == 10 10)) break;; break
if (i if (i % 2 == 0) continue ; Console.Write( Console .Write("{0} "{0} ", ", i); } Console.WriteLine(); Console .WriteLine(); } }
Foreach Statement: The foreach statement is new to the C family of languages; it is used for looping through the elements of an array or a collection.
class ForEachTest { static void Main(string Main(string[] [] args) { int[] int [] num = new int[] int[] { 0, 1, 2, 3, 4, 5, 6,7,8 }; foreach (int i in num) { System..Console System Console.WriteLine(i); .WriteLine(i); } } }
Array An array is the collection of similar type of objects. Array in C# is different for the array of C++ and other languages because they are objects. This provides them useful methods and property. Arrays allow a group of elements of a particular type to be stored in a contiguous block of memory. Array types derive from System.Array and are declared in C# using brackets ([]). Syntax- datatype [] array-name; e.g.- int [] age; The square brackets ([]) tell the C# compiler that you are declaring an array, and the type specifies the type of the elements it will contain. In the previous example, age is an array of integers. Instantiate an array using the new keyword. For example: age = new int[5]; This declaration sets aside memory for an array holding five integers.
Multidimensional Array:
Multidimensional Arrays of two two types Rectangular Array and Jagged Array Rectangular Array represents n-dimensional blocks. e.g.- int [ , ,] age = new int[17,20,34]; Jagged Arrays are arrays of arrays.
int [][][] books = new int [3][][]; for (int i = 0; i < 3; i++) { books[i] = new int [4][]; for (int int j j = 0; j < 4; j++) books[i][j] = new int [5]; } // assign an element books1 [1 [1,1,1] = books [1 [1][1 ][1][1 ][1] = 7;
Indexer: Indexers are usually known known as smart array in C#.It is used for treating treating object as an array.Defining an indexer in C# is much like same as defining properties. Or we can s ay that an indexer is a member that enables an object to be indexed in the same way as an array. Syntax this [argument list] { get { // Write here some code for Get } set { // Write here some code for Get } }
Collections: Collections are the enumerable data structure in C# that can be assessed using indexes or keys. Types of collections in C# are given belowSystem.Collections namespace This provides a lot of classes, methods and properties to interact with the varying data structures that are supported by it. The interfaces that are defined in this namespace include:
• • • • •
IEnumerable IEnumerator ICollection IList IDictionary System.Collections.Stack
• •
System.Collections.Queue Both are derived from ICollection Interface. The collections that inherit the IDictionary interface include: System.Collections.SortedList System.Collections.Hashtable The IList interface represents represents collections that only have value. The following are the classes that extend this interface. System.Array System.Collections.ArrayList System.Collections.Specialized.StringCollection
Concrete Collection Classes: ArrayList class- This works by maintaining an internal array of objects that is replaced with a larger array when it reaches its capacity of elements. dynamically sized array of Boolean values. It is more more memoryBitArray classclass- It is a dynamically efficient than a simple array of bools bools because it uses only one one bit for each value. Hashtable class- A Hashtable is a standard dictionary (key/value) data structure that uses a hashing algorithm to store and and index values values efficiently. Queue class- A Queue is a standard first-in, first-out (FIFO) data structure, providing simple operations to enqueue, dequeue, peek, etc. SortedList class-A class-A SortedList is a standard dictionary data structure that uses a binarychop search to index efficiently. Stack class- A Stack is a standard last-in first-out (LIFO) data structure. StringCollection class- A StringCollection is a standard collection data structure for storing strings.
Inheritance In C#, the specialization relationship is generally implemented by using inheritance. Inheritance is also provides provides the reusability, or we can say say that extracts some some features from one class to another class.
class Bird { public Bird() { Console.WriteLine( Console .WriteLine("Bird "Bird } public void Greet() { Console.WriteLine( Console .WriteLine("Bird "Bird } public void Talk() { Console.WriteLine( Console .WriteLine("Bird "Bird } public virtual void Sing() { Console.WriteLine( Console .WriteLine("Bird "Bird }
constructor"); constructor");
says Hello"); Hello" );
talk"); talk");
song"); song");
} class Peacock : Bird { public Peacock() { Console.WriteLine( Console .WriteLine("Peacock "Peacock constructor"); constructor"); } public new void Talk() { Console.WriteLine( Console .WriteLine("Peacock "Peacock talk"); talk"); } public override void Sing() { Console.WriteLine( Console .WriteLine("Peacock "Peacock song"); song"); } } Bird a1 = new Bird(); a1.Talk(); a1.Sing(); a1.Greet(); Bird a2 = new Peacock(); a2.Talk(); a2.Sing(); a2.Greet();
Types of Inheritance: In Object Oriented Programming concept there are 3 types of inheritances. 1. Single Inheritance, 2. Multiple Inheritance 3. Multilevel Inheritance
Single Inheritance: public class A { } public class B:A { }
Multiple Inheritance: public class A { } public class B
{ } public class C:A,B { }
Multilevel Inheritance: public class A { } public class B:A { } public class C:B { } In the above three types C# don't proved Multiple Inheritance. As there is conflict of multiple override methods in base classes (say A, B in above example) As in Place C# give another feature called Interfaces using interfaces you can achieve multiple Inheritance feature. Polymorphism Poly means many and morph means form. Thus, polymorphism refers to being able to use many forms of a type without regard to the details. Creating Polymorphic Types: For creating polymorphism there are two steps1. Create a base class with virtual methods. 2. Create derived classes that override the behavior of the base class’s virtual methods. To create a method in a base class that supports polymorphism, mark the method as virtual. Example.
public class BaseClass { public virtual void DoWork() { } public virtual int WorkProperty { get { return 0; } }
} public class DerivedClass : BaseClass { public override void DoWork() { } public override int WorkProperty() { get { return 0; } } }
Properties In C#, properties are natural extension of data fields. But C# provides a built in mechanism called properties. Usually inside a class, we declare a data field as private and will provide a set of public. In C#, properties are defined using the property declaration syntax. The general form of declaring a property is as follows. { get { } set { } } SET and GET methods to access the data fields, since the data fields are not directly accessible out side the class. We must use the set/get methods to access the data fields. Example:
using System System;; class Myproperty { private int x; public int X { get { return x; } set { x = value;
} } } class Myprop { public static void Main() { Myproperty mc = new Myproperty(); mc.X = 10 10;; int xVal = mc.X; Console.WriteLine(xVal); Console .WriteLine(xVal); //Displays 10 } }
Properties and Inheritance The properties of a Base class can be inherited to a Derived class.
using System System;; class Base { public int X { get { Console.Write( Console .Write("Base "Base GET"); GET"); return 10 10;; } set { Console.Write( Console .Write("Base "Base SET"); SET"); } } } class Derived : Base { } class MyClient { public static void Main() { Derived d1 = new Derived(); d1.X = 10 10;; Console.WriteLine(d1.X); Console .WriteLine(d1.X); //Displays 'Base SET Base GET 10' } }
Properties & Polymorphism A Base class property can be polymorphic overridden in a Derived class. But remember that the modifiers like virtual, override etc are using at property level, not at accessor level.
using System System;; class Base { public virtual int X { get { Console.Write( Console .Write("Base "Base GET"); GET"); return 10 10;; } set { Console.Write( Console .Write("Base "Base SET"); SET"); } } } class Derived : Base { public override int X { get { Console.Write( Console .Write("Derived "Derived GET"); GET" ); return 10 10;; } set { Console.Write( Console .Write("Derived "Derived SET"); SET" ); } } } class MyClient { public static void Main() { Base b1 = new Derived(); b1.X = 10 10;; Console.WriteLine(b1.X); Console .WriteLine(b1.X); //Displays 'Derived SET Derived GET 10' } }
Abstract Properties
It is declared as abstract by using the keyword abstract. Remember that an abstract property in a class carries no code at all. The get/set assessors are simply represented with a semicolon. In the derived class we must implement both set and get assess ors.
using System System;; abstract class Abstract { public abstract int X { get; set; } } class Concrete : Abstract { public override int X { get { Console.Write( Console .Write("" GET"); GET" ); return 10 10;; } set { Console.Write( Console .Write("" SET"); SET"); } } } class MyClient { public static void Main() { Concrete c1 = new Concrete(); c1.X = 10 10;; Console.WriteLine(c1.X); Console .WriteLine(c1.X); //Displays 'SET GET 10' } }
Attributes Attributes contains a powerful method of associating declarative information with C# code for types, methods, properties. Once associated with a program entity, the attribute can be queried at run time and used in any number of ways. Uses of Attributes: •
Associating help documentation with program entities (through a Help attribute).
•
Associating value editors to a specific type in a GUI framework (through a Value Editor attribute).
using System System;; [AttributeUsage(AttributeTargets.All)] public class HelpAttribute : System System..Attribute { public readonly string Url; public string Topic { get { return topic; } set {
// Topic is a named parameter
topic = value; } } public HelpAttribute(string HelpAttribute(string url) // url is a positional parameter { this.Url this .Url = url; } private string topic; }
When do we need attributes ? 1. The System.O System.ObsoleteA bsoleteAttribu ttribute te attribute attribute that we we have just just described described is a good good example of how an attribute is used by the compiler, certain standard attributes which are only destined for the compiler are not stored in the assembly. 2. An attribute attribute can be be consumed consumed by the the CLR during during execution execution.. For example example the .NET .NET Framework offers the System.ThreadStaticAttribute attribute. When a static field is marked with this attribute the CLR makes sure that during the execution, there is only one version of this field per thread. 3. An attribute attribute can be be consumed consumed by a debugg debugger er during executi execution. on. Hence, Hence, the System.Diagnostics.DebuggerDisplayAttribute attribute allows personalizing the display of an element of the code the state of an object for example) during debugging.
4. St Stru ruc cts 5. Structure Structure is the collectio collection n of dissimilar dissimilar data types. types. A struct struct is a simple user-defin user-defined ed type, a lightweight lightweight alternative to classes. Structs are somewhat more more efficient in their use of memory in arrays. The C# struct is a lightweight alternative to a class. It can do almost the same as a class, but it's less "expensive" to use a struct rather than a class.
class Program { static void Main(string Main(string[] [] args) { Home home; Home = new Home("Blue" Home( "Blue"); ); Console.WriteLine(Home.Describe( Console .WriteLine(Home.Describe( )); Home = new Home("Red" Home( "Red"); ); Console.WriteLine(Home.Describe( Console .WriteLine(Home.Describe( )); Console.ReadKey(); Console .ReadKey(); } } struct Home { private string color; public Home(string Home( string color) { this.color this .color = color; } public string Describe() { return "This Home is " + Color; } public string Color { get { return color; } set { color = value; } } }
A struct is a value type and and a class is a reference type. When a struct is created, the variable to which the struct is assigned holds the struct's actual data. and When an object of the class is created, the variable to which the object is assigned holds only a reference to that memory. When the struct is assigned to a new variable, it is copied and When the object reference is assigned to a new variable. The new variable and the original variable therefore contain two separate copies of the same data. Changes made to one copy do not affect the other copy. the new variable refers to the original object.
In general, classes are used to model more complex behavior, or data that is intended to be modified after a class object is created. Structs are best suited for small data structures that contain primarily data that is not intended to be modified after the struct is created. When to Use Structures?
•
If the instances are relatively small If the instance life-time is going to be very short If you are going to embed the instance into some other instances
•
Delegate
• •
•
A delegate in C# language allows us to reference reference a method. If we are using using a C or C++ then we would sound familiar because a delegate because it is basically a function pointer. Delegates have other uses in addition to event handling. Delegate maintains three important pieces of information : 1. The name of the method on which it make calls. 2. Any argument (if any) of this method. 3. The return value (if any) of this method.
•
What is a Function Pointer? Function Pointers are pointers, i.e. variables, which point to the address of a function. • •
Types of Delegate Delegates are of two types 1.Single 1.Single Cast delegate public delegate delegate (parameters) name>(parameters)
• •
•
2.Multi 2.Multi Cast delegate public delegate void (parameters) Advantage of using Delegate Dynamic binding can be done by using delegate because we can call more than one methods at a time dynamically by calling the delegate in which the methods is defined. Example
namespace delgnew { public delegate int Delg(int Delg(int x, int y); public class Math { public static int Add(int Add( int x, int y) { return x + y; }
public static int Multiply(int Multiply(int x, int y) { return x * y; } } class Fun { static void Main(string Main(string[] [] args) { Delg del1 = new Delg(Math Delg(Math.Add); .Add); int add1 = del1(7 del1(7, 7); Console.WriteLine( Console .WriteLine("7 "7 + 7 = {0}\n", {0}\n" , add1); Delg del2 = new Delg(Math Delg(Math.Multiply); .Multiply); int multiply1 = del2(7 del2( 7,7); Console.WriteLine( Console .WriteLine("7 "7 * 7 = {0}", {0}" , multiply1); Console.ReadLine(); Console .ReadLine(); } } }
Static Delegates Denoting static field is meaning that it will not be modified. You can invoke delegates without declaring a local delegate instance. Just pass in the static delegate of the class. Delegates as Properties The problem with static delegates is that they they must be instantiated whether or not they are are ever used. Event An event might might be a button push, a menu selection in short short we can cay that something happens and you must respond to it. You cannot predict the order in which events will arise. For exampleexample- when you click a button, it might r aise the Click event. When you add to a drop-down list, it might raise a List Changed event. Defining Event
using System System;; class Eventtest { public event EventHandler myfun { add { Console.WriteLine Console .WriteLine ("Event ("Event Fired"); Fired" );
} remove { Console.WriteLine Console .WriteLine ("Controlled" ("Controlled"); ); } } static void Main() { Eventest et = new Eventtest(); et.myfun += new EventHandler (et.DoNothing); et.myfun -= null null;; } void DoNothing (object (object sender, EventArgs e) { } }
An event allows a class (or other object) to send notifications to other classes (or objects) that something has occurred. In simple ter ms an event is the outcome of a specific action. If you have developed programmers in graphical user interfaces (GUI) then you are very familiar with Event handling. When a user interacts with a GUI control (e.g., clicking a button on a form), one or more methods are executed in response to the above event. Events can also be generated without user interactions. Event handlers are methods in an object that are executed in response to some events occurring in the application.
What is Exception? The exceptions are anomalies that occur during the execution of a program. Exception handling is a mechanism in .NET framework to detect and handle handle run time time errors. They can be because of user, logic or system errors. If a user (programmer) do not provide a mechanism t o handle these anomalies, the .NET run time environment provide a default mechanism, which terminates the program execution. In C# there are three keywords Try, Try, Catch and Finally for handling exceptions. In try block statements it might throw an exception whereas catch handles that caused by try block if one exists. The finally block is used for doing any clean up process. The statement in finally block always executes. e.g.
try { // this can cause an exception. } catch (Type x) { // for handling the exception. }
finally { //this will execute. }
Handling Exceptions In catch block, if don't use a brackets or arguments, we can catch all exceptions occurred inside a try block. Even we can use a catch block with an Exception type parameter to catch all exceptions happened inside the try block. Since in C#, all exceptions are directly or indirectly inherited from the Exception class. e.g. class newexp { public static void Main() { int a = 0; int div = 0; try { div = 100 /a; Console.WriteLine( Console .WriteLine("This "This will not print"); print" ); } catch { Console.WriteLine( Console .WriteLine("oException" "oException" ); } Console.WriteLine( Console .WriteLine("Result "Result is {0}",div); {0}",div); } }
Exceptions Classes Following are some common exception classes. SystemExceptionSystemException- This exception means a failed run-time check used as a base class for other. AccessExceptionAccessException- This exception means failure to access a type member, such as a method or field. ArgumentException- This exception means an argument to a method was invalid. ArgumentNullException- This exception means a null argument was passed to a method that doesn't accept it. ArgumentOutOfRangeException-This ArgumentOutOfRangeExceptionThis exception means argument value is out of range. ArithmeticException- This exception means arithmetic over – or underflow has occurred. ArrayTypeMismatchException- This exception means attempt to store the wrong type of object in an array. BadImageFormatException- This exception means image is in the wrong format. •
•
• •
•
•
•
•
•
CoreException- This exception means base class for exceptions thrown by the runtime. DivideByZeroException- This exception means an attempt was made to divide by zero. FormatException- This exception means the format of an ar gument is wrong. IndexOutOfRangeException- This exception means an array index is out of bounds. InvalidCastExpression- This exception means an attempt was made to cast to an invalid class. InvalidOperationException- This exception means a method was called at an invalid time. MissingMemberException- This exception means an invalid version of a DLL was accessed. NotFiniteNumberException- This exception means a number is not valid. NotSupportedException- This exception means indicates that a method is not implemented by a class. NullReferenceException- This exception means attempt to use an unassigned reference. OutOfMemoryException- This exception means not enough memory to continue execution. StackOverflowException- This exception means a stack has overflow.
•
What is thread ?
•
Threads are typically created when you want a program to do two things at once.
•
Starting Threads
•
•
• •
•
•
•
• •
•
•
•
The simplest way to create a thread is to create a new instance of the Thread class. The Thread constructor takes a single argument: a delegate type. The CLR provides the ThreadStart delegate class specifically for this purpose, which points to a method you designate. This allows you to construct a thread and to say to it "when you start, run this method." The ThreadStart delegate declaration is: public delegate void ThreadStart( );
•
Example for Creating Thread:
•
using System System;; using System System..Threading Threading;; public class CreatingThread { static void Main(string Main(string[] [] args) { Thread MyThread = new Thread Thread((new ThreadStart(ThreadProc)); MyThread.Start(); MyThread.Join(); } protected static void ThreadProcess() { for (int i = 0; i < 100 100;; i++) { Console.WriteLine(i); Console .WriteLine(i);
} } } •
Creating a Thread of Execution:
using System System;; using System System..Threading Threading;; class MyThread { public int count; string thrdName; public MyThread(string MyThread(string name) { count = 0; thrdName = name; } public void run() { Console.WriteLine(thrdName Console .WriteLine(thrdName + " starting."); starting." ); do { Thread.Sleep( Thread .Sleep(500 500); ); Console.WriteLine( Console .WriteLine("In "In " + thrdName +", +", count is " + count); count++; } while while(count (count < 10 10); ); Console.WriteLine(thrdName Console .WriteLine(thrdName + " terminating."); terminating." ); } } public class MultiThread { public static void Main() { Console.WriteLine( Console .WriteLine("Main "Main thread starting."); starting." ); MyThread mt = new MyThread("Child MyThread("Child #1"); #1"); Thread newThrd = new Thread Thread((new ThreadStart(mt.run)); newThrd.Start(); do { Console.Write( Console .Write("." "."); ); Thread.Sleep( Thread .Sleep(100 100); ); } while (mt.count != 10 10); ); Console.WriteLine( Console .WriteLine("Main "Main thread ending."); ending." ); } }
• •
Joining Threads To join thread1 (t1) onto thread2 (t2), write: t2.Join( );
Joining the current thread to each thread in the collection in turn:
foreach (Thread myThread in myThreads) { myThread.Join( ); } Console.WriteLine( Console .WriteLine("All "All my threads are done."); done." ); •
Create multiple threads of execution
using System System;; using System System..Threading Threading;; class MyThread { public int count; public Thread thrd; public MyThread(string MyThread(string name) { count = 0; thrd = new Thread Thread((new ThreadStart(this ThreadStart(this.run)); .run)); thrd.Name = name; thrd.Start(); } void run() { Console.WriteLine(thrd.Name Console .WriteLine(thrd.Name + " starting."); starting."); do { Thread.Sleep( Thread .Sleep(500 500); ); Console.WriteLine( Console .WriteLine("In "In " + thrd.Name +", +", count is " + count); count++; } while while(count (count < 10 10); ); Console.WriteLine(thrd.Name Console .WriteLine(thrd.Name + " terminating."); terminating." ); } } public class MoreThreads { public static void Main() { Console.WriteLine( Console .WriteLine("Main "Main thread starting."); starting." ); MyThread mt1 = new MyThread("Child MyThread("Child #1"); #1" ); MyThread mt2 = new MyThread("Child MyThread("Child #2"); #2" ); MyThread mt3 = new MyThread("Child MyThread("Child #3"); #3" ); do { Console.Write( Console .Write("." "."); ); Thread.Sleep( Thread .Sleep(100 100); ); } while (mt1.count < 10 || mt2.count < 10 || mt3.count < 10 10); );
Console.WriteLine( Console .WriteLine("Main "Main thread ending."); ending." ); } }
Suspending Threads To cause your thread to sleep for one second, you can invoke the static method of Thread, Sleep, which suspends the thread in which it is invoked: Thread.Sleep( Thread .Sleep(1000 1000); );
Killing Threads For killing a thread Abort( ) method is used. This causes a ThreadAbortException exception to be thrown, which the thread can catch, and thus provides the thread with an opportunity to clean up any resources it might have allocated. catch (ThreadAbortException ThreadAbortException)) { Console.WriteLine( Console .WriteLine("[{0}] "[{0}] Aborted! Cleaning up...", up..." , Thread.CurrentThread.Name); Thread .CurrentThread.Name); } Example for Suspending, resuming, and stopping a thread:
using System System;; using System System..Threading Threading;; class MyThread { public Thread thrd; public MyThread(string MyThread(string name) { thrd = new Thread Thread((new ThreadStart(this ThreadStart(this.run)); .run)); thrd.Name = name; thrd.Start(); } void run() { Console.WriteLine(thrd.Name Console .WriteLine(thrd.Name + " starting."); starting."); for((int i = 1; i <= 1000 for 1000;; i++) { Console.Write(i Console .Write(i + " "); "); if ((i%10 ((i%10)== )==0 0) { Console.WriteLine(); Console .WriteLine(); Thread.Sleep( Thread .Sleep(250 250); ); } } Console.WriteLine(thrd.Name Console .WriteLine(thrd.Name + " exiting."); exiting." ); } } public class SuspendResumeStop { public static void Main() {
MyThread mt1 = new MyThread("My MyThread("My Thread"); Thread" ); Thread.Sleep( Thread .Sleep(1000 1000); ); // // let child thread start executing mt1.thrd.Suspend(); Console.WriteLine( Console .WriteLine("Suspending "Suspending thread."); thread." ); Thread.Sleep( Thread .Sleep(1000 1000); ); mt1.thrd.Resume(); Console.WriteLine( Console .WriteLine("Resuming "Resuming thread."); thread." ); Thread.Sleep( Thread .Sleep(1000 1000); ); mt1.thrd.Suspend(); Console.WriteLine( Console .WriteLine("Suspending "Suspending thread."); thread." ); Thread.Sleep( Thread .Sleep(1000 1000); ); mt1.thrd.Resume(); Console.WriteLine( Console .WriteLine("Resuming "Resuming thread."); thread." ); Thread.Sleep( Thread .Sleep(1000 1000); ); Console.WriteLine( Console .WriteLine("Stopping "Stopping thread."); thread." ); mt1.thrd.Abort(); mt1.thrd.Join(); // mt1.thrd.Join(); // wait for thread to terminate Console.WriteLine( Console .WriteLine("Main "Main thread terminating."); terminating." ); } } Synchronization Synchronization is provided by a lock on the object, which prevents a second thread from barging in on your object until the first thread is finished with it.
Microsoft Visual Studio Visual Studio is an integrated development environment (IDE) developed by Microsoft. It can be used to develop console and graphical user interface applications along with Windows Forms applications, web sites, web applications, and web services in both native code together with managed code for all platforms supported by Microsoft Windows, Windows Mobile, Windows CE.
Architecture It does not support any programming language, solution or tool intrinsically. Instead, it allows plugging in various types of functionality, that is coded as a VSPackage. The IDE provides three services: SVsSolution, which provides the ability to enumerate projects and solutions; SVsUIShell, which provides windowing and UI functionality (including tabs, toolbars and tool windows) SVsShell, which deals with registration of VSPackages. In addition, the IDE also manages for coordinating and enabling communication between services. All editors, designers, project types and other tools are implemented as VSPackages. Visual Studio uses COM to access the VSPackages. The Visual Studio SDK also includes the Managed Package Framework (MPF), which is a set of managed wrappers around the COM-interfaces that allow the Packages to be written in any CLI compliant language. However, MPF does not provide all the functionality exposed by the Visual Studio
COM interfaces. The services can then be consumed for creation of other packages, which add functionality to the Visual Studio IDE.
Features of Microsoft Visual Studio
Code editor: Code editor that supports syntax highlighting and code completion using IntelliSense for not only variables, functions and methods but also language constructs like loops and queries. Debugger: It works both as a source-level debugger and as a machine-level debugger. It works with both managed code as well as native code and can be used for debugging applications written in any language supported by Visual Studio. Designer: It includes a host of visual designers to aid in the development of applications. These tools includes •
Windows Forms Designer: It includes a palette of UI widgets and controls (including buttons, progress bars, labels, layout containers and other controls) that can be dragged and dropped on a form surface.
•
•
•
•
•
WPF(Windows Presentation Foundation) Designer: It is used to author user interfaces targeting Windows Presentation Foundation. It supports all WPF functionality including data binding and automatic layout management. Web designer/development: It is used for developing ASP.NET applications and supports HTML, CSS and JavaScript. It uses a code-behind model to link with ASP.NET code. From Visual Studio 2008 onwards, the layout engine used by the web designer is shared with Microsoft Expression Web. Class designer: The Class Designer can generate C# and VB.NET code outlines for the classes and methods. It can also generate class diagrams from hand-written classes. Data designer: The data designer can be used to graphically edit database schemas, including typed tables, primary and foreign keys and constraints. It can also be used to design queries from the graphical view. Mapping designer: The mapping designer is used by LINQ to SQL to design the mapping between database schemas and the classes that encapsulate the data.
Other tools ToolBox Explorer
Open Tabs Browser: It is used to list all open tabs and to switch between them. It is invoked using CTRL+TAB. Properties Editor: It is used to edit properties in a GUI pane inside Visual Studio.
Object Browser: Browser: It can be used to browse the namespaces (which are arranged hierarchically) in managed assemblies.
Solution Explorer: Explorer : It is used to manage and browse the files in a solution.
Team Explorer: It is used to integrate the capabilities of Team Foundation Server, the Revision Control System into the IDE (and the basis for Microsoft's CodePlex hosting environment for open source projects). In addition to source control it provides the ability to view and manage individual work items (including bugs, tasks and other documents) and to browse TFS statistics. Data Explorer: It is used to manage databases on Microsoft SQL Server instances. Server Explorer: It tool is used to manage database connections on an accessible computer.
Included products •
•
•
• •
Microsoft Visual C++: It is Microsoft's implementation of the C and C++ compiler and associated languages-services and specific tools for integration with the Visual Studio IDE. Microsoft Visual C#: Microsoft's implementation of the C# language, targets the .NET Framework, along with the language services that lets the Visual Studio IDE support C# projects. Microsoft Visual Basic: Microsoft's implementation of the VB.NET language and associated tools and language services. It was introduced with Visual Studio .NET (2002).
Creating Windows Application For creating a new project you need to first load Visual Studio .NET and select Windows Application as in Figure F igure below . Type the name of the project below along with selecting the desired location to store your files.
•
•
going to design a simple application for for adding Designing The Interface: We are going values in List Box from from textbox input input by the user, for this this will need to add the the following items onto your form. GroupBox Label ComboBox Textbox Button ListBox
•
Adding The Code: When this form loads we need to populate the ComboBox with the appropriate values. Add the following code by clicking on the form on the outside of the groupBox. You should see something like this: write this code on Form Load Event-
•
•
private void Form1_Load(object Form1_Load(object sender, EventArgs e) { comboBox1.Items.Add("Dr." comboBox1.Items.Add( "Dr."); ); comboBox1.Items.Add("Er." comboBox1.Items.Add( "Er."); ); comboBox1.Items.Add("Mr." comboBox1.Items.Add( "Mr."); ); comboBox1.Items.Add("Mrs." comboBox1.Items.Add( "Mrs."); ); comboBox1.Items.Add("Ms." comboBox1.Items.Add( "Ms."); ); comboBox1.Focus(); }
•
Double-click on the OK button and add the following code:
private void button1_Click(object button1_Click(object sender, EventArgs e) {
listBox1.Items.Add(comboBox1.Text + " " +textBox1.Text listBox1.Items.Add(comboBox1.Text +textBox1.Text + " " + textBox2.Text textBox2. Text); ); textBox1.Text textBox1.Text = "" "";; textBox2.Text textBox2.Text = "" "";; comboBox1.Text comboBox1.Text = "" "";; comboBox1.Focus(); } When we want to allow the user to clear all fields entered into the listBox, we will need to go back like we did above to the visual designer and double-click on the Clear List button, this should again switch to a code view and allow you to add the following code-
•
private void button2_Click(object button2_Click(object sender, EventArgs e) { listBox1.Items.Clear(); comboBox1.Focus(); }
And finally we want to allow the user to be able to close the application when they want. To show you another way to allow the user to close the program aside from that catchy X in the upper right-hand corner, I have provided a button entitled Close.
•
private void button3_Click(object button3_Click(object sender, EventArgs e) { this.Dispose(); this .Dispose(); }
Controls System.Windows.Forms.Control class This class defines the basic functionality of the System.Windows.Forms.Control class controls, which is why many properties and events in the controls. Some controls, named custom or user controls, derive from another class: System.Windows.Forms.UserControl . This class is itself derived from the Control class and provides the functionality we need to create controls ourselves. Properties All controls have a number of properties that are used to manipulate the behavior of the control. The base class of most controls, Control, has a number of properties that other controls either inherit directly or override to provide some kind of custom behavior.
Name
Availability
Anchor
Read/Write
BackColor
Read/Write
Bottom
Dock
Read/Write Read/Write
Description It tells how control behaves when its container is resized. about background color of a control. You can specify the distance from the top of the window to the bottom of the control. This is not the same as specifying the height of the control. by this property you can make a control dock to the edges of a window. Enabled to true usually means that the control can receive input from the user. Setting Enabled to false usually means that it cannot. foreground color of the control.
Enabled
Read/Write
ForeColor
Read/Write
Height
Read/Write
distance from the top to the bottom of the control.
Left
Read/Write
left edge of the control relative to the left edge of the window.
Name
Read/Write
name of the control. This name can be used to reference the control in code.
Parent
Read/Write
Right
Read/Write
TabIndex
Read/Write
TabStop
Read/Write
Tag
Read/Write
Top
Read/Write
Visible
Read/Write
Width
Read/Write
parent of the control. right edge of the control relative to the left edge of the window. number the control has in the tab order of its container. Specifies whether the control can be accessed by the Tab key. This value is usually not used by the control itself, and is there for you to store information about the control on the control itself. When this property is assigned a value through the Windows Form designer, you can only assign a string to it. The top edge of the control relative to the top of the window. Specifies whether or not the control is visible at runtime. width of the control.
Events When a user clicks a button or presses a button, you as the programmer of the application, want to be told that this has happened. To do so, controls use events. The Control class defines a number of events that are common to the controls we'll use in this chapter.
Name
Description
MouseMove Occurs continually as the the mouse travels over over the control. control. Occurs when the mouse pointer is over a control and a MouseUp mouse button is released. Click
Occurs when a control is clicked. In some cases, this event will also occur when a user presses Enter.
Occurs when a control is double-clicked. Handling the Click event on some controls, such as the Button control DoubleClick will mean that the DoubleClick event can never be called. DragDrop DragEnter DragLeave DragOver KeyDown
Occurs when a drag-and-drop operation is completed, in other words, when an object has been dragged over the control, and the user releases the mouse button. Occurs when an object being dragged enters the bounds of the control. Occurs when an object being dragged leaves the bounds of the control. Occurs when an object has been dragged over the control. Occurs when a key becomes pressed while the control has focus. This event always occurs before KeyPress and KeyUp.
KeyPress
Occurs when a key becomes pressed, while a control has focus. This event always occurs after KeyDown and before KeyUp. The difference between KeyDown and KeyPress is that KeyDown passes the keyboard code of the key that has been pressed, while KeyPress passes the corresponding char value for the key.
KeyUp
Occurs when a key is released while a control has focus. This event always occurs after KeyDown and KeyPress.
GotFocus
LostFocus
Occurs when a control receives focus. Do not use this event to perform validation of controls. Use V alidating and Validated instead. Occurs when a control looses focus. Do not use this event to perform validation of controls. Use V alidating and Validated instead.
Occurs when the mouse pointer is over a control and a mouse button is pressed. This is not the same as a Click MouseDown event because MouseDown occurs as soon as the button is pressed and before it is released. Paint
Occurs when the control is drawn.
Validated
This event is fired when a control with the CausesValidation property set to true is about to receive focus. It fires after the Validating event finishes and indicates that validation is complete.
Validating Validating
Fires when a control control with the CausesValid CausesValidation ation property property set to true is about to receive focus. Note that the control which is to be validated is the control which is
losing focus, not the one that is receiving it.
The Button Control The button control exists on just about any Windows dialog you can think of. A button is primarily used to perform three kinds of tasks: For closing a dialog with a state (for example, OK and Cancel buttons) For performing an action on data entered on a dialog (for example clicking Search after entering some search criteria) For opening another dialog or application (for example, Help buttons) Properties of Button Control
Name
Availability
Description
FlatStyle
Read/Write
If you set the style to PopUp, the button will appear flat until the user moves the mouse pointer over it. When that happens, the button pops up to its normal 3D look.
Enabled
Read/Write
Enabled property to false means that the button becomes grayed out and nothing happens when you click it.
Image
Read/Write
Allow you to specify an image (bitmap, icon etc.), which will be displayed on the button.
Imag ImageA eAlig lign n Read Read/W /Writ rite e
Button Events
With this property, you can set where the image on the button should appear.
The most used event of a Button is the Click event. This occurs whenever a user clicks the button, by which we mean pressing the left mouse button and releasing it again while over the button. This means that if you left-click on the button and then draw the mouse away from the button before releasing it the Click event will not be raised. Also, the Click event is raised when the button has focus and t he user press Enter. If you have a button on a form, you should always handle this event. Adding the Event Handlers When you double-click the control two things happens in the code behind the form. First of all, a subscription to the event is created in the InitializeComponent() method: this.btnEnglish.Click += new System this.btnEnglish.Click System.EventHandler( .EventHandler(this this.btnEnglish_Click); .btnEnglish_Click); The second thing that happens, is that the event handler itself is added.
private void button1_Click(object button1_Click(object sender, EventArgs e) { label1.Text label1.Text = "You have clicked the button!!!"; button!!!" ; }
Label and Link Label The label is a simple control with one purpose only: to present a caption or short hint to explain something on the form to the user. Visual Studio.NET includes two label controls that are able to present them selves to the user in two distinct ways: Label, the standard Windows label LinkLabel, a label like the standard one (and derived from it), but presents itself as an internet link (a hyperlink)
The TextBox Control Text boxes should be used when you want the user to enter text that you have no knowledge of at design time (for example the name of the user). The primary function of a text box is for the user to enter text, but any characters can be entered, and it is quite possible to force the user to t o enter numeric values only. Properties of TextBox
Name
Availability
CausesValidationRead/Write
Chara Characte cterC rCasi asing ng Read Read/W /Wri rite te
Description When a control that has this property set to true is about to receive focus, two events are fired: Validating and Validated. You can handle these events in order to validate data in the control that is losing l osing focus. This may cause the control never to receive focus. The related events are discussed below. A valu value e indi indica catin ting g if the the Tex TextB tBox ox cha chang nges es the the case of the text entered. The possible values are: q Lower: All text entered into the text box is converted lower case.
q Normal: No changes are made to the text. q Upper: All text entered into the text box is converted to upper case.
Read/Write
A value that specifies the maximum length in characters of any text, entered into the TextBox. Set this value to zero it the maximum limit is limited only by available memory.
Read/Write
Indicates if this is a Multiline control. A Multiline control is able to show multiple lines of text.
Pass Passwo word rdCh Char ar
Read Read/W /Wri rite te
Specifies if a password character should replace the actual characters entered into a single line textbox. If the Multiline property is true then this has no effect.
ReadOnly
Read/Write
A Bo Boolean indicating if if th the te text is is read on only.
ScrollBars
Read/Write
Selec electe ted dTex Text
Read Read/W /Wri rite te
MaxLength
Multiline
Specifies if a multilane text box should display scrollbars. The The text text that that is sele select cted ed in the tex text box box.
Selecti SelectionL onLeng ength th Read/W Read/Writ rite e
The number of characters selected in the text. If this value is set to be larger than the total number of characters in the text, it is reset by the control to be the total number of characters minus the value of SelectionStart.
Sele Select ctio ionS nSta tart rt
Read Read/W /Wri rite te
The The sta start rt of the the sel selec ecte ted d tex textt in in a text text box. box.
Read/Write
Specifies if a multiline text box should automatically wrap words if a line exceeds the width of the control.
WordWrap
Events of TextBox
Name
Description
Enter GotFocus Leave Validating Validated
These six events occur in the order they are listed here. They are known as "Focus Events" and are fired whenever a controls focus changes, with two exceptions. Validating and Validated are only fired if the control that receives focus has the CausesValidation property set to true. The reason why it's the receiving control that fires the event is that there are times where you do not want to validate the control, even if focus changes. An example of this is if the user clicks a Help button.
LostFocus KeyDown KeyPress
These three events are known as "Key Events". They allow you to monitor and change what is entered into your controls.
KeyDown and KeyUp receive the key code corresponding to the key that was pressed. This allows you to determine if special keys such as Shift or Control and F1 were pressed. KeyUp
Change
KeyPress, on the otherhand, receives the character corresponding to a keyboard key. This means that the value for the letter "a" is not the same as the letter "A". It is useful if you want to t o exclude a range of characters, for example, only allowing numeric values to be entered. Occurs whenever the text in the textbox is changed, no matter what the change.
TextBox Test
First Design a form on choosing choosing New Project of Windows Application. and then then set the properties of label, button and forms like shown in above picture. Adding the events Code for Ok Button Click
okbtn_Click(object sender, EventArgs e (private void okbtn_Click(object }
if (nametxt. (nametxt.Text Text == "" || textBox2.Text textBox2. Text == "" || textBox3.Text textBox3. Text == "" || textBox4.Text textBox4. Text == if ("" } MessageBox.Show( MessageBox .Show("Please "Please fill all Information", Information" , "Alert" "Alert",, ,MessageBoxButtons.OKCancel ;(MessageBoxIcon.Information { else } ;string output Concatenate the text values of the four TextBoxes // this.nametxt. .nametxt.Text Text + "\r\n ;"output = "Name: " + this this.textBox2. .textBox2.Text Text + "\r\n ;"output += "Address: " + this this.textBox3. .textBox3.Text Text + "\r\n ;"output += "Occupation: " + this this.textBox4. .textBox4.Text Text ;output += "Age: " + this Insert the new text //
this.textBox5. .textBox5.Text Text = output ;this { {
Code for Help Button Click-
private void button1_Click(object button1_Click(object sender, EventArgs e) { string output; output = "Name = Enter Your name\r\n" name\r\n";; output += "Address = Enter Your address\r\n"; address\r\n"; output += "Occupation = Enter Occupation\r\n";; Occupation\r\n" output += "Age = Enter Your age"; age" ; // Insert the new text this.textBox5. this .textBox5. Text = output; } Adding Events on TextBoxEvent on TextBox Leave Event-
private void nametxt_Leave(object nametxt_Leave(object sender, EventArgs e) { if (nametxt. if (nametxt.Text Text == "" "")) {
nametxt.BackColor = Color.Red; } } Event on TextBox Keypress Event-
private void nametxt_KeyPress( nametxt_KeyPress(object object sender, KeyPressEventArgs e) { if (nametxt.BackColor if (nametxt.BackColor == Color.Red) { nametxt.BackColor = Color.Snow; } }
Radio Button
Radio buttons themselves as a label with a dot to the left of it, which can be either selected or not. You should use the radio buttons when you want to give the user a choice between several mutually exclusive options. for Example, if you want to ask for the gender of the user. To group radiobuttons together so that they create one logical unit you must use a GroupBox control. By first placing a group box on a form, and then placing the RadioButton controls you need within the borders of the group box, the RadioButton controls will know to change their state to reflect that only one within the group box can be selected. If you do not place them within a group box, only one RadioButton on the form can be selected at any given time.
CheckBox Controls A CheckBox traditionally displays itself as a label with a small box with a checkmark to the left of it. You should use the check box when you want to allow the user to choose one or more options. An example could be a questionnaire asking which operating systems the user has tried (for example, Windows 95, Windows 98, Linux, Max OS X, and s o on.)
RadioButton Properties Name
Availability
Appearan rance
Read/Wri /Write te
AutoCheck
Read/Write
CheckAlign
Checked
Description A RadioButton can be displayed either as a label with a circular check to the left, middle or right of it, or as a standard button. When it is displayed as a button, the control will appear pressed when selected and 3D otherwise. When this property is true, a check mark is displayed when the user clicks the radio button. When it is false, the check mark is not displayed by default.
Read/Write
By using this property, you can change the alignment of the radio button. It can be left, middle, and right.
Read/Write
Indicates the status of the control. It is true if the control has a check mark, and false otherwise.
RadioButton Events
Name
Description
This event is sent when the check of the RadioButton changes. If there is more than one RadioButton control on CheckChanged the form or within a group box, this event will be sent twice, first to the control, which was checked and now becomes unchecked, then to the control which becomes checked. This event is sent every time the RadioButton is clicked. This is not the same as the change event, because clicking a RadioButton twice or more times in succession only changes Click the checked property once ? and only if it wasn't checked already.
CheckBox Properties Name Availability
CheckStateRead/Write
ThreeState ThreeState Read/Write Read/Write
Description Unlike the RadioButton, a CheckBox can have three states: Checked, Indeterminate, and Unchecked. When the state of the check box is Indeterminate, the control check next to the label is usually grayed, indicating that the current value of the check is not valid or has no meaning under the current circumstances. An e xample of this state can be seen if you select several files in the Windows Explorer and look at their properties. If some files are ReadOnly and others are not, the ReadOnly checkbox will be checked, but grayed indeterminate. When this property is false, the user will not be able to change the CheckBox' state to Indeterminate. You can, however, still change the state of the check box to Indeterminate from code.
CheckBox Events Name
Description
Occurs whenever the Checked property of the check box changes. Note that in a CheckBox where the ThreeState property is true, it is possible to click the CheckedChanged check box without changing the Checked property. This happens when the check box changes from checked to indeterminate state. Occurs whenever the CheckedState property changes. As Checked and Unchecked are both possible values of the CheckedState property, this event will be sent CheckedStateChanged whenever the Checked property changes. In addition to that, it will also be sent when the state changes from Checked to Indeterminate.
Example: In following image i have created a window form for saving information of student like personal info and subjects of his/her. For this you have to drag and drop 4 textboxes, 2 radiobuttons, radiobuttons, 5 labels and 3 buttons. buttons. Change all controls properties like in picture.
1
2
3
4
In figure 2 if user direct click on ok button then he/she will get massage for alert to fill all information. In Figure 3 if user fill personal information and then click on Ok button then he/she will get alert message for choosing gender. And in figure 4 if user not choose subject and click on ok button button then he will get another alert message for choosing choosing subject. To making all these validation you have to write following code on Ok button Click. Code For Ok Button Click:
private void button2_Click(object button2_Click(object sender, EventArgs e) { if (textBox1. if (textBox1.Text Text == "" || textBox2.Text textBox2. Text == "" || textBox4.Text textBox4. Text == "" "")) { MessageBox.Show( MessageBox .Show("Please "Please fill all personal information", information" , "Warning", "Warning", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning); }
else if (radioButton1.Checked if (radioButton1.Checked == false && radioButton2.Checked == false false)) { MessageBox.Show( MessageBox .Show("Please "Please select Gender", Gender", "Warning" "Warning",, MessageBoxButtons.OKCancel, MessageBoxIcon.Warning); } else if (checkedListBox1. if (checkedListBox1.Text Text== =="" "")) { MessageBox.Show( MessageBox .Show("Please "Please select Subjects", Subjects", "Warning" "Warning",, MessageBoxButtons.OKCancel, MessageBoxIcon.Warning); } else { if (radioButton1.Checked) if (radioButton1.Checked) { // Concatenate the text values of the four TextBoxes output = "Name: " + this this.textBox1. .textBox1.Text Text + "\r\n" "\r\n";; output += "Address: " + this this.textBox2. .textBox2. Text + "\r\n" "\r\n";; output += "Course: " + this this.textBox4. .textBox4.Text Text + "\r\n" "\r\n";; output += "Sex: " + this this.radioButton1. .radioButton1.Text Text + "\r\n" "\r\n";; output += "Subject:" "Subject:";; foreach (string sub in checkedListBox1.CheckedItems) output += " " + sub; } if (radioButton2.Checked) if (radioButton2.Checked) { // Concatenate the text values of the four TextBoxes output = "Name: " + this this.textBox1. .textBox1.Text Text + "\r\n" "\r\n";; output += "Address: " + this this.textBox2. .textBox2. Text + "\r\n" "\r\n";; output += "Course: " + this this.textBox4. .textBox4.Text Text + "\r\n" "\r\n";; output += "Sex: " + this this.radioButton2. .radioButton2.Text Text+ +"\r\n" "\r\n";; output += "Subject:" "Subject:";; foreach (string sub in checkedListBox1.CheckedItems) output += " " + sub; } this.textBox3. this .textBox3.Text Text = output; } }
Now if you to give condition condition for user user that he should must choose at least three subjects then you can add code for this on Checklistbox Leave Event. Like following code. Code for Leave Event on Checklist Box.
private void checkedListBox1_Leave( checkedListBox1_Leave(object object sender, EventArgs e) { int count = checkedListBox1.CheckedItems.Count; { if (count<=3 (count<=3) MessageBox.Show( MessageBox .Show("Your "Your minimum choice is Three subject"); subject"); } }
Final output will show like in below figure
GroupBox Control Windows Forms GroupBox controls are used to provide a most important facility for grouping other controls. Typically, you use group boxes t o subdivide a form by function. For example, you may have an order form that specifies mailing options such as which overnight carrier to use. Grouping all options in a group box gives the user a logical visual
cue. The GroupBox control is similar to the Panel control; however, only the GroupBox control displays a caption, and only the Panel control can have scroll bars.
Group Box Properties
Group Box Event:
Rich TextBox Control Like the normal TextBox, the RichTextBox control is derived from TextBoxBase. Because of this, it shares a number of features with the TextBox, but is much more diverse. Where a TextBox is commonly used with the purpose of obtaining short text strings from the user, the RichTextBox is used to display and e nter formatted text (for example bold, underline, and italic). It does so using a standard for formatted text called Rich Text Format or RTF. RichTextBox Properties
Name
Availability
Description
CanRedo
Read only
This property is true if something s omething has been undone, that can be reapplied, otherwise false.
CanUndo
Read only
This property is true if it is possible to perform an undo action on the RichTextBox, otherwise it is false.
Read on only
This property holds the name of an action that be used to redo something that has been undone in the RichTextBox.
DetectUrls
Read/Write
Set this property to true to make the control detect URLs and format them (underline as in a browser).
R tf
Read/Write
This corresponds to the Text property, except that this holds the text in RTF.
RedoActionName
SelectedRtf
Read/Write
SelectedText
Read/Write
Selec Selecti tion onAli Align gnme ment nt
Read Read/W /Writ rite e
Use this property to get or set the selected text in the control, in RTF. If you copy this text to another application, for example, MS Word, it will retain all formatting. Like SelectedRtf you can use this property to get or set the selected text. Unlike the RTF version of the property however, all formatting is lost. This represents the alignment of the selected text. It can be Center, Left, or Right.
SelectionBullet
Read/Write
Use this property to find out if t he selection is formatted with a bullet in front of it, or use it to insert or remove bullets.
BulletIndent
Read/Write
Use this property to specify the number of pixels a bullet should be indented.
SelectionColor
Read/Write
Allow you to change the color of the text in the selection.
SelectionFont
Read/Write
Allow you to change to font of the text in the selection.
SelectionLength
Read/Write
Using this property, you either set or retrieve the length of a selection.
Read only
This property holds information about the selection. It will tell you if one or more OLE objects are selected or if only text is selected.
SelectionType
Show ShowSe Selec lecti tion onMa Margi rginRead nRead/W /Writ rite e
If you you set set thi this s prope property rty to to true true,, a margin will be shown at the left of the RichTextBox. This will make it easier for