Reading Content From The File: Application 61: File Writing Demo
Reading Content From The File: Application 61: File Writing Demo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace FileWriteDemo
{
class Program
{
static void Main(string[] args)
{
string filepath;
Console.WriteLine("Enter the file path:");
filepath = Console.ReadLine();
FileInfo fobj = new FileInfo(filepath);
if (!fobj.Exists)
{
string content;
Console.WriteLine("\nEnter content to write:");
content = Console.ReadLine();
Console.WriteLine("\nWritten successfully!");
}
else
Console.WriteLine("File already exists.");
Output:
using System;
using System.IO;
namespace FileReadDemo
{
class Program
{
static void Main(string[] args)
{
string filepath;
Console.WriteLine("Enter the file path:");
filepath = Console.ReadLine();
FileInfo fobj = new FileInfo(filepath);
if (fobj.Exists)
{
StreamReader sr = new StreamReader(filepath);
string content = sr.ReadToEnd();
Console.WriteLine(content);
sr.Close();
}
else
Console.WriteLine("File not found.");
Console.Read();
}
}
}
Multi Tasking:
Def: Ability of the OS, that is able to perform more than one task, at-a-time
(simultaneously) is called as ―Multi-Tasking‖.
As a part of this, OS allocates the CPU clock (CPU capacity) for each task.
Note: Just like multi-tasking, OS allocates the CPU clock for each thread.
Threading Architecture:
.NET Application
OS
Thread 1
CLR
Thread 2
Thread 3
Processor
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace SimpleThreadingDemo
{
class ThreadingDemo
{
private void FirstMethod()
{
for (int i = 1; i <= 300; i++)
Console.Write("i=" + i + " ");
}
private void SecondMethod()
{
for (int j = 1; j <= 300; j++)
Console.Write("j=" + j + " ");
}
public void Display()
{
Thread th1 = new Thread(FirstMethod);
Thread th2 = new Thread(SecondMethod);
th1.Start();
th2.Start();
Output:
The thread state specifies the current status of the thread. Sometimes, the thread
automatically switches from one state to another state automatically; at some other times, you
can switch its state by using the methods offered by ―Thread‖ class.
The following diagram called ―Thread Life Cycle‖ describes the different states of a
thread.
Ready
Start()
Running
Sleeping
Suspend()
Resume()
Suspended
Automatic / Abort()
Dead
“Thread”classmethods:
o thobj.Start()
This method starts-up the thread execution.
o Thread.Sleep(mille_sec)
This method puts the thread under ―Sleeping‖ state, up to a certain no. of mille
seconds. When the given no. of mille seconds are completed, automatically the
thread execution will be continued.
o thobj.Suspend()
This is similar to ―Sleep()‖ method, but here, no time limit will be given. That
means whenever the ―Suspend()‖ method is called, the thread will be put under
―Suspended‖ state, until the ―Resume()‖ method is called.
o thobj.Resume()
This is to continue the thread execution that is under ―Suspended‖ state. This
method won‘t work if the thread is not under ―Suspended‖ state.
o thobj.Abort()
This is close the thread execution completely, at any time. Once, if the ―Abort()‖
method is called, the thread can‘t be started or resumed. This is the end of every
thread life cycle.
namespace ThreadLifeCycleDemo
{
class ThreadingDemo
{
private void FirstMethod()
{
for (int i = 1; i <= 50; i++)
{
Console.Write("i=" + i + " ");
Thread.Sleep(1000);
}
}
private void SecondMethod()
{
for (int j = 1; j <= 50; j++)
{
Console.Write("j=" + j + " ");
Thread.Sleep(1000);
if (j == 20)
th1.Suspend();
else if (j == 30)
th1.Resume();
}
}
Anonymous Methods
This is used to create a method, without any name.
Syntax:
delegate()
{
//some code
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace AnonymousMethodsDemo
{
class ThreadingDemo
{
public void Display(string name)
{
Thread th1 = new Thread(delegate()
{
while (true)
{
Console.WriteLine("Welcome to " + name);
Thread.Sleep(500);
}
});
th1.Start();
}
}
Console.Read();
}
}
}
Output:
Implementation:
Create the object of ―SpeechSynthesizer‖ class:
SpeechSynthesizer ss = new SpeechSynthesizer();
Set the volume (1 to 100):
ss.Volume = n;
Set the speed of speaking (-10 to +10):
ss.Rate = n;
Change the voice gender and age:
ss.SelectVoiceByHints(VoiceGender.xxxx, VoiceAge.xxxx);
Speak the text:
ss.SpeakAsync(―message‖);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Speech.Synthesis;
namespace SpeechTranslationDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter text to speak:");
string TextToSpeak = Console.ReadLine();
ss.SelectVoiceByHints(VoiceGender.Female, VoiceAge.Child);
ss.SpeakAsync(TextToSpeak);
Console.Read();
}
}
}
Output:
Memory Management
Every application requires some amount of memory to run.
That memory will be allocated in the primary memory (RAM).
For every variable, individual memory will be allocated.
The RAM contains two memory locations.
o Stack RAM
o Heap
Now, we need to understand, where the
application memory is getting allocated in the Stack
RAM.
The storage area in the RAM depends on the
―data type‖ that you are using for declaring the
Heap
variable in the program.
The data types are two types in C#
o Value Types
o Reference Types
2) Reference Types:
Def: Whenever a data type is designed based on a class, it can be called as
―Reference Type‖.
The following are the reference types in C#:
1) Classes
2) Interfaces
3) String, Object
Reference types support inheritance.
Object
ValueType
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ObjectClassMethods
{
class Program
{
static void Main(string[] args)
{
int x = 100;
int y = 100;
Console.WriteLine();
if (x.Equals(y))
Console.WriteLine("x is equal to y");
else
Console.WriteLine("x is not equal to y");
string s = x.ToString();
Console.WriteLine("\nThe integer value after converting into string is: " + s);
Console.Read();
}
}
}
Output:
Object 1
Object 2
Object 3
Object 4
Note: The above functionality is in-built in ―Garbage collector‖ component. Anyhow, there is a
provision for the programmer to command the garbage collector to perform ―garbage collection‖
at run time, programmatically. Then use the following method from ―System.GC‖ class.
Syn: System.GC.Collect();
Introduction:
In relational database system, data is organized in the form of tables, on which you can
write SQL queries to retrieve the required data according to the requirement in the
application.
But you can‘t write a query on the non-database data, which in the form of objects in the
application. There, you can write the queries using the new concept called ―LINQ‖.
You can write queries on arrays, objects, databases and XML using LINQ.
Note: Before writing the LINQ queries, you should import the ―System.Linq‖
namespace..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LINQtoArrayDemo
{
class Program
{
static void Main(string[] args)
{
//data source
int[] numbers = { 2, 12, 10, 5, 15, 4, 62 };
//ling query
IEnumerable<int> result = from n in numbers where n <= 10 select n;
Console.Read();
}
}
}
Output:
In the above application, the array contains few numbers. After executing the query, you
got only the numbers, which are less than 10. In this manner, you can execute the queries on
data sets (after learning ADO.NET) also.
LINQ Syntax:
Mandatory clauses:
from clause
in clause
select clause
1. from clause: This is used to specify the iteration variable name. This acts as alias name
for the data source.
2. in clause: This is used to specify the main data source for the query.
3. let clause (optional): This is used to declare a new identifier with a value, that is to be
used during the query execution.
4. where clause (optional): This is most frequently used optional clause, using which
you can specify the condition in the query.
5. orderby clause (optional): This is used to specify the sorting expression if required.
6. select clause: This is used to specify the object, which is required in the query results.
7. group by (optional): This is similar to ―group by‖ clause in SQL. This retrieves grouped
data, based on a column.
Note: The result of a LINQ query should be assigned into a IEnumerable<data type> type
variable. IEnumerable is an interface.
Library: System.Collections.Generic.IEnumerable
Student.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LINQtoObjectsDemo
{
class Student
{
//fields
public int StudentID;
public string Name;
public string Course;
public int Marks;
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LINQtoObjectsDemo
{
class Program
{
static void Main(string[] args)
{
//data source
Student[] stu = { new Student(101, "Prakash", "MBA", 765),
new Student(102, "Pradeep", "MBA", 471),
new Student(103, "Pushpa", "Msc", 590),
new Student(104, "Purna", "MCA", 223),
new Student(105, "Purnima", "MCA", 450)};
Console.Read();
}
}
}
goes to
Student.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LINQtoObjectsDemo
{
class Student
{
//fields
public int StudentID;
public string Name;
public string Course;
public int Marks;
//constructor
public Student(int StudentID, string Name, string Course, int Marks)
{
this.StudentID = StudentID;
this.Name = Name;
this.Course = Course;
this.Marks = Marks;
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LINQwithLambaExpressions
{
class Program
{
static void Main(string[] args)
{
//data source
Student[] stu = { new Student(101, "Prakash", "MBA", 765),
new Student(102, "Pradeep", "MBA", 471),
new Student(103, "Pushpa", "Msc", 590),
new Student(104, "Purna", "MCA", 223),
new Student(105, "Purnima", "MCA", 450)};
Console.Read();
}
}
}
Types of Errors:
1) Compile Time Errors: The errors occurred after compiling the program, are called as
―compile time errors‖.
2) Run Time Errors: The errors occurred during the execution of the program, are called
as ―run time errors‖.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExceptionDemo1
{
class Program
{
static void Main(string[] args)
{
string[] Cities = { "Vijayawada", "New Delhi", "Banglore", "Hyderabad" };
Console.WriteLine(Cities[3]);
Console.WriteLine(Cities[4]);
Console.Read();
}
}
}
In the above code, the highlighted line contains an error, because it is trying to access an
array element which is in out of range of the array. So, it leads to abnormal application
termination at run time.
try
{
---------------------;
---------------------;
---------------------;
---------------------;
}
catch (Exception ex)
{
--------------------;
--------------------;
}
finally
{
--------------------;
--------------------;
}
1) try block:
The try block contains the actual code, which
is to be executed. try
{
After every try block, there should catch
---------------------;
block without fail. ---------------------;
The system tries to execute the code in the ---------------------;
---------------------;
try block. }
During the execution, if any exception
occurs, then the execution control automatically goes to catch block.
At the same time, the ―try‖ block throws the exception to the catch block in the
form of an object. That object is called as ―exception object‖.
2) catch block:
This is also known as ―error handler‖.
This is followed by the try block.
The catch block will be executed if any
exception is occurred during the execution catch (Exception ex)
of try block. {
--------------------;
The catch block contains necessary code --------------------;
which displays an error message to the }
user.
This receives the exception, thrown by the try block, in the form of an object. In
the following syntax, ―ex‖ is the ―Exception object‖. The ―Exception‖ is the class
for the exception object.
Library: System.Exception
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExceptionDemo2
{
class Program
{
static void Main(string[] args)
{
try
{
string[] Cities = { "Vijayawada", "New Delhi", "Banglore", "Hyderabad" };
Console.WriteLine(Cities[3]);
Console.WriteLine(Cities[4]);
}
catch (Exception ex)
{
Console.WriteLine("Error occurred.");
}
finally
{
Console.WriteLine("This is 'finally' block.");
Console.Read();
}
}
}
}
Already we have discussed that the catch block generates an error message, when an exception
occurs. That error message can be of two types.
1. User Defined Message
2. System Defined Message
Note: Based on the situation, the above specified exception classes could be used.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExceptionDemo3
{
class Program
{
static void Main(string[] args)
{
try
{
int n1, n2, n3;
n3 = n1 / n2;
Output:
Note: If you want to handle more than one type of exception for the same try block, then you
need to write multiple catch blocks.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExceptionDemo4
{
class Program
{
static void Main(string[] args)
{
try
{
int n1, n2, n3;
n3 = n1 / n2;
Console.WriteLine("Result is: " + n3);
}
catch (DivideByZeroException ex)
{
Console.WriteLine("This is divide by zero exception.");
}
catch (OverflowException ex)
{
Console.WriteLine("This is overflow excpetion.");
}
catch (FormatException ex)
{
Console.WriteLine("This is invalid cast exception.");
}
Console.Read();
}
}
}
Output:
The“EventLog”
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
namespace EventLogDemo
{
class Program
{
static void Main(string[] args)
{
try
{
string filename = "c:\\sample.txt";
StreamReader sr = new StreamReader(filename);
Debugging
Bug: An error.
Debugging: Removing the bugs.
.NET offers more features for debugging. To start with the .NET application debugging, you
should create the break points.
Break Points
i) Definition: A break point is a point in the program, where the application execution
control pauses until you press ―F10‖ key. In the code, that line is highlighted with red
color.
ii) Creating a break point: Just click on the left side margin of the required line.
iv) Observing the values of variables or objects: While you are executing the
application with break points, to know the current value of any variable or object,
just place the mouse pointer over it.
The ―Immediate‖ window resides at bottom side of Visual Studio IDE. It will automatically
appear at run time. If not, press ―Ctrl + Alt + I‖.
This window is used to know the current values of the required variables, objects or data
members, which is not possible to find the value by just placing the mouse pointer over
it.
Locals window
It automatically displays all the current local variables along with their values.
To open this window, while running the application, get into the Visual Studio and press
―Ctrl+D‖ and the ―L‖.
Overviewof“ClassLibrary”Project
Global Assembly Cache (GAC): All the shared assemblies should be saved in the GAC. GAC
offers the following advantages.
Unique identification of the shared assemblies.
Avoids the DLL hell (replacement of an assembly related to one application, by another
application).
Faster accessibility.
Strong Name Keys (SNK): The ―strong name key‖ is a file, which acts as a unique
identifier, for the shared assemblies, stored in the GAC. In other words, GAC recognizes the
assembly with this strong name only.
In this example,
Class Library Project: SharedAssemblyLibrary
Console Application Project: SharedAssemblyDemo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SharedAssemblyLibrary
{
public class MyLibraryClass
{
public bool IsValidLogin(string Username, string Password)
{
if (Username == "system" && Password == "manager")
return true;
else
return false;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharedAssemblyLibrary;
namespace SharedAssemblyDemo
{
class Program
{
static void Main(string[] args)
{
MyLibraryClass mlc = new MyLibraryClass();
Console.Read();
}
}
}
Output:
A Windows Application
Double click on the controls and write the code in the ―Code window‖.
For example, double click on ―OK‖ button and write the following code:
And then, double click on ―Cancel‖ button and write the following code:
While you design the controls, the Visual Studio generates some automatic code in the
“Form1.Designer.cs” file.
To open this file, Open Solution Explorer, Expand ―Form1‖, then double click on
―Form1.Designer.cs‖.
For example, you can see the automatic generated code for the previous ―Login‖
example:
Form1.Designer.cs:
namespace WindowsFormsApplication1
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed;
otherwise, false.</param>
this.button2.TabIndex = 3; this.button2.Text
= "Cancel";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(64, 48);
this.label1.Margin = new System.Windows.Forms.Padding(5, 0, 5, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(104, 19);
this.label1.TabIndex = 4;
this.label1.Text = "User Name:";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(64, 107);
this.label2.Margin = new System.Windows.Forms.Padding(5, 0, 5, 0);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(93, 19);
this.label2.TabIndex = 5;
this.label2.Text = "Password:";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 19F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(492, 244);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.textBox2);
this.Controls.Add(this.textBox1);
this.Font = new System.Drawing.Font("Tahoma", 12F,
System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Margin = new System.Windows.Forms.Padding(5, 4, 5, 4);
this.Name = "Form1";
this.Text = "Login";
this.ResumeLayout(false);
this.PerformLayout();
#endregion
Don‘t worry about the above automatic generated code; it will be generated automatically,
while you design the form in the Design window.
The entire code is generated in a method called ―InitializeComponent()‖.
Finally, coming to a conclusion; every form contains two files:
o Form1.Designer.cs
Contains the code for designing (Automatically generated code by Visual Studio).
o Form1.cs
Contains the actual functionality code (Written by the Programmer).
Form1.cs
importing section;
namespace ProjectName
{
public partial class FormName : Form
{
public FormName()
{
InitializeComponent();
}
}
}
In the importing section, you can import the necessary namespaces that you want.
The namespace name should be same as project name.
A user-defined class with the form name is to be defined.
It should be the sub class of "System.Windows.Forms.Form" class; as it offers some
visual design, properties, methods and events for the user-defined form class.
It will be defined as a public class (this is optional). Whenever it is a public class, in
future, it can be accessed from other projects also.
It should be defined as "partial" class, as its definition is written in the following two files.
o Form1.cs
o Form1.Designer.cs
It should contain a constructor, with a statement called ―InitializeComponent();‖,
which calls the designer code that is generated in ―Form1.Designer.cs‖ file.
Generally, when you ―Start‖ the windows application project, automatically the ―Form1‖
will be appeared on the screen.
Then don‘t think like directly Form1 will be opened.
In fact, when you click on ―Start‖ option, the Main() method will be invoked first.
Like Console Applications, Main() method is located in ―Program.cs‖ file.
Application.Run(new Form1());
This statement creates a new Form1 class object and that object will be
shown on the screen.
Common Properties
Property Description
Name Specifies the name of the control.
Text Specifies the displayable text of the control.
BackColor Specifies the background color of the control.
ForeColor Specifies the foreground color of the control.
Font Specifies the font style of the control‘s text.
Enabled Enables / Disables the control.
Visible Displays / Hides the control.
Specifies the mouse pointer style, when the mouse is over on the control at
Cursor
run time.
Size Specifies the Width and Height of the control.
Location Specifies the X and Y co-ordinations of the control‘s position on the form.
TextAlign Specifies the position of the text in the control.
Specifies the image that is to be displayed in the control along with the
Image
text.
ImageAlign Specifies the position of the image in the control
TabIndex Specifies the index of the control in the tab order.
ContextMenuStrip Contains the reference of the respective context menu control.
Common Events
Event Description
Click Executes when the user clicks the control run time.
DoubleClick Executes when the user double-clicks the control at run time.
MouseMove Executes when the mouse pointer is moves across the control.
MouseEnter Executes when the mouse pointer is focused on to the control.
MouseLeave Executes when the mouse pointer is out of the control.
Executes when any key is pressed on the keyboard, while the focus is on
KeyPress
the control.
Enter Executes when the focus is entered into the control.
Leave Executes when the focus got out of the control.
Event: An event is a run time action that can be performed by the user.
Let us practice the above properties and events on the button control.
Design
button1:
Text: What’s the time now?
button2:
Text: Show Me a Random Number
ForeColor: Green
button3:
Text: Exit
BackColor: Purple
ForeColor: Yellow
Image: c:\close.jpg
ImageAlign: MiddleLeft
FlatStyle: Popup
Font: Lucida Sans, Bold, 11
TabIndex controlname.TabIndex = n;
Event Handling
Def: The event handling includes with executing some code, whenever the user
performs an action.
The necessary code is to be written in a special method. That method is called as ―Event
Handler‖.
Event Handler:
An event handler is a method, which will be called automatically, whenever the user
performs certain event at run time.
The event handler should be defined in the form class.
Syntax:
First, in the design window, select the form or control, for which you want to create the
event handler.
Open ―Properties‖ window, and click on ―Events‖
option.
Select the required event, for which you want to create
the event handler.
Press Enter.
Then the event handler will be created in the code
window.
Design
button1:
Text: Click Me
BackColor: DarkRed
ForeColor: Yellow
I. Common Controls
1) Button
2) Label
3) TextBox
4) PictureBox
5) LinkLabel
6) CheckBox
7) RadioButton
8) ListBox
9) ComboBox
10) DomainUpDown
11) NumericUpDown
12) DateTimePicker
13) MonthCalendar
The ―System.Windows.Forms.Form‖ class offers few properties, methods and events for each
user-defined form class.
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
(or)
WindowState this.WindowState = System.Windows.Forms.FormWindowState.Minimized;
(or)
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
Cursor this.Cursor = System.Windows.Forms.Cursors.xxxxx;
Opacity this.Opacity = n;
Structures 7) System.Drawing.Color
8) System.Drawing.ContentAlignment
9) System.Windows.Forms.ImageLayout
Enumerations
10) System.Windows.Forms.FormWindowState
11) System.Windows.Forms.FormBorderStyle
Design
Form1:
Text: Click the form
Design
button1:
Text: Red
Name: btnRed
button2:
Text: Green
Name: btnGreen
button3:
Text: Blue
Name: btnBlue
Design
button1:
Text: Normal
Name: btnNormal
button2:
Text: Minimize
Name: btnMinimize
button3:
Text: Maximize
Name: btnMaximize
button3:
Text: Exit
Name: btnExit
Design
button1:
Text: Show Background Image
Name: btnShowBackgroundImage
button2:
Text: Clear Background Image
Name: btnClearBackgroundImage
Properties of Button
Property Description
Name Specifies the name of the control.
Text Specifies the displayable text of the control.
BackColor Specifies the background color of the control.
ForeColor Specifies the foreground color of the control.
Font Specifies the font style of the control‘s text.
Enabled Enables / Disables the control.
Visible Displays / Hides the control.
Cursor Specifies the mouse pointer style, when it is over on the control.
Size Specifies the Width and Height of the control.
Location Specifies the X and Y co-ordinations of the control‘s position on the form.
TextAlign Specifies the position of the text in the control.
Specifies the image that is to be displayed in the control along with the
Image
text.
ImageAlign Specifies the position of the image in the control
TabIndex Specifies the index of the control in the tab order.
ContextMenuStrip Contains the reference of the respective context menu control.
FlatStyle Specifies style of the button. (Flat / Popup / Standard / System)
Events of Button
Event Description
Click Executes when the user clicks the control run time.
DoubleClick Executes when the user double-clicks the control at run time.
MouseMove Executes when the mouse pointer is moves across the control.
MouseEnter Executes when the mouse pointer is focused on to the control.
MouseLeave Executes when the mouse pointer is out of the control.
Executes when any key is pressed on the keyboard, while the focus is on
KeyPress
the control.
Enter Executes when the focus is get into the control.
Leave Executes when the focus is out of the control.
API: System.Windows.Forms.Label
Naming Convension: lblxxxxxx
Properties of Label
Property Description
Name Specifies the name of the control.
Text Specifies the displayable text of the control.
BackColor Specifies the background color of the control.
ForeColor Specifies the foreground color of the control.
Font Specifies the font style of the control‘s text.
Enabled Enables / Disables the control.
Visible Displays / Hides the control.
Cursor Specifies the mouse pointer style, when it is over on the control.
Size Specifies the Width and Height of the control.
Specifies the X and Y co-ordinations of the control‘s position on the
Location
form.
TextAlign Specifies the position of the text in the control.
Specifies the image that is to be displayed in the control along with
Image
the text.
ImageAlign Specifies the position of the image in the control
TabIndex Specifies the index of the control in the tab order.
ContextMenuStrip Contains the reference of the respective context menu control.
Enables / disables automatic sizing of the control, based on the
AutoSize
text.
Events of Label
Event Description
Click Executes when the user clicks the control run time.
DoubleClick Executes when the user double-clicks the control at run time.
MouseMove Executes when the mouse pointer is moves across the control.
MouseEnter Executes when the mouse pointer is focused on to the control.
MouseLeave Executes when the mouse pointer is out of the control.
Executes when any key is pressed on the keyboard, while the focus
KeyPress
is on the control.
Enter Executes when the focus is entered into the control.
Leave Executes when the focus is out of the control.
Properties of TextBox
Property Description
Name Specifies the name of the control.
Text Specifies the displayable text of the control.
BackColor Specifies the background color of the control.
ForeColor Specifies the foreground color of the control.
Font Specifies the font style of the control‘s text.
Enabled Enables / Disables the control.
Visible Displays / Hides the control.
Cursor Specifies the mouse pointer style, when it is over on the control.
Size Specifies the Width and Height of the control.
Specifies the X and Y co-ordinations of the control‘s position on the
Location
form.
Specifies the position of the text in the control (Left / Center /
TextAlign
Right)
Specifies the image that is to be displayed in the control along with
Image
the text.
ImageAlign Specifies the position of the image in the control
TabIndex Specifies the index of the control in the tab order.
ContextMenuStrip Contains the reference of the respective context menu control.
Enables / disables read-only nature of the textbox. In the read only
ReadOnly
textbox, the user can not enter any text.
Enables / disables multiple lines in the text box. By default, the text
MultiLine
box will be single-line textbox.
This is used in multi line textboxes, which automatically moves the
WordWrap
cursor to the next line, when the current line exceeds.
Scrollbars Enables / disables scroll bars in the textbox.
PasswordChar Used to specify the password display character. Ex: *
Specifies the maximum no. of characters that can be entered in the
MaxLength
textbox.
Events of TextBox
Event Description
TextChanged Executes when any character is typed / removed in the textbox.
Click Executes when the user clicks the control run time.
DoubleClick Executes when the user double-clicks the control at run time.
MouseMove Executes when the mouse pointer is moves across the control.
MouseEnter Executes when the mouse pointer is focused on to the control.
MouseLeave Executes when the mouse pointer is out of the button.
Executes when any key is pressed on the keyboard, while the focus
KeyPress
is on the control.
Methods of TextBox
Method Description
Clear() Clears all the contents of the textbox and makes it empty.
Focus() Moves the focus to the control.
Design
label1:
Text: Enter First Value:
Name: lblFirstValue (Continued…)
button3:
textBox1: Name: btnMultiply
Name: txtFirstValue Text: *
label2: button4:
Text: Enter Second Value: Name: btnDivide
Name: lblSecondValue Text: /
button1: label3:
Name: btnAdd Name: lblResult
Text: + Text: Result:
button2: textBox3:
Name: btnSubtract Name: txtResult
Text: - ReadOnly: True
Design
label1:
Text: Enter your text here:
Name: lblSourceText
textBox1:
Name: txtSourceText
label2:
Text: Copied Text:
Name: lblDestinationText
button1:
Name: txtDestinationText
ReadOnly: True
label3:
Text: To:
Name: lblTo
textBox2:
Name: txtTo
button1:
Name: btnGo
Text: GO
textBox3:
Name: txtNumbers
ReadOnly: True
MultiLine: True
ScollBars: Vertical
Used to take the choice from the user. The check box can be checked or
un-checked by the user.
API: System.Windows.Forms.CheckBox
Naming Convension: chkxxxxxx
Properties of CheckBox
Property Description
Name Specifies the name of the control.
Represents the current status of the check box, whether it is
Checked
checked or un-checked.
Text Specifies the displayable text of the control.
BackColor, ForeColor, Font, Enabled, Visible, Cursor, Size, Location, TextAlign, Image, ImageAlign,
TabIndex, ContextMenuStrip
Events of CheckBox
Event Description
CheckedChanged Executes when the user checks / un-checks the checkbox.
Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave
Methods of CheckBox
Method Description
Focus() Moves the focus to the control.
5) RadioButton
Used to take the choice from the user. We have to implement two or
more radio buttons. At run time, any one of the radio buttons can be
selected.
API: System.Windows.Forms.RadioButton
Naming Convension: rbxxxxxx
Properties of RadioButton
Property Description
Name Specifies the name of the control.
Text Specifies the displayable text of the control.
Represents the current status of the check box, whether it is
Checked
checked or un-checked.
BackColor, ForeColor, Font, Enabled, Visible, Cursor, Size, Location, TextAlign, Image, ImageAlign,
TabIndex, ContextMenuStrip
Events of RadioButton
Event Description
CheckedChanged Executes when the user checks / un-checks the radio button.
Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave
Methods of RadioButton
Method Description
Focus() Moves the focus to the control.
Design
label1:
Text: Select Background Color:
Name: lblBackgroundColor
radioButton1: Text:
Beige Name:
rbBeige
radioButton2:
Text: Light Green
Name: rbLightGreen
radioButton3:
Text: Light Yellow
Name: rbLightYellow
radioButton4: Text:
Bisque Name:
rbBisque
API: System.Windows.Forms.LinkLabel
Naming Convension: lnkxxxxxx
Properties of LinkLabel
Property Description
Name Specifies the name of the control.
Text Specifies the displayable text of the control.
LinkColor Specifies the default link color
VisitedLinkColor Specifies the visited link color
ActiveLinkColor Specifies the active link color
BackColor, ForeColor, Font, Enabled, Visible, Cursor, Size, Location, TextAlign, Image, ImageAlign,
TabIndex, ContextMenuStrip
Events of LinkLabel
Event Description
LinkClicked Executes when the user clicks on the link.
Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave
Methods of LinkLabel
Method Description
Focus() Moves the focus to the control.
Design
linkLabel1:
Text: My Link Label:
Name: linkLabel1
7) PictureBox
Used to display an image on the form, at desired place.
API: System.Windows.Forms.PictureBox
Naming Convension: picxxxxxx
Properties of PictureBox
Property Description
Name Specifies the name of the control.
Image Specifies the image, which is to be displayed in the control.
Specifies mode of the image sizing in the control.
SizeMode
(Normal, Stretch, Auto Size, Center, Zoom)
BackColor, Enabled, Visible, Cursor, Size, Location, ContextMenuStrip
Events of PictureBox
Event Description
Click Executes when the user clicks on the picture box.
DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave
Design button2:
label1: Text: Clear Image
Text: Enter image path: Name: btnClearImage
Name: lblEnterImagePath
label2: radioButton3:
textBox1: Text: Size Mode: Text: Auto Size
Name: txtImagePath ForeColor: Red Name: rbAutoSize
button1: radioButton1: radioButton4:
Text: Show Text: Normal Text: Center
Name: btnShow Name: rbNormal Name: rbCenter
pictureBox1: radioButton2: radioButton5:
BorderStyle: Fixed3D Text: Stretch Text: Zoom
Name: picBoxImage Name: rbStretch Name: rbZoom
API: System.Windows.Forms.Panel
Naming Convension: pnlxxxxxx
Properties of Panel
Property Description
Name, BackColor, ForeColor, Font, Enabled, Visible, Size, Location, BackgroundImage,
BackgroundImageLayout, ContextMenuStrip, BorderStyle
Events of Panel
Event Description
Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave
Note: When you want to create multiple groups of radio buttons, then use the panel or group
box control to group-up those radio buttons.
API: System.Windows.Forms.GroupBox
Naming Convension: grpxxxxxx
Properties of GroupBox
Property Description
Name, Text, BackColor, ForeColor, Font, Enabled, Visible, Size, Location, BackgroundImage,
BackgroundImageLayout, ContextMenuStrip
Events of GroupBox
Event Description
Enter, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Leave
This contains multiple options (items). Among those items, the user can
select any one option. In some list boxes, multiple items also can be
selected. Those list boxes are called as ―Mutiple item selection list
boxes‖.
API: System.Windows.Forms.ListBox
Naming Convension: lstxxxxxx
Properties of ListBox
Property Description
Items Contains the list of items, that can be displayed in the list box.
Specifies mode of the item selection.
None – No item can be selected.One - Single item can only be selected
SelectionMode MultiSimple – Multiple items can be selected, directly by clicking on the items.
MultiExtended – Multiple items can be selected, with Shift+Click or Ctrl+Click.
Events of ListBox
Event Description
SelectedIndexChanged, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Leave
Methods of ListBox
Property Description
ListboxName.Items.Add(―xxxxx‖) Adds a new item at the end of the list box items.
ListboxName.Items.Insert(index,
Inserts a new item at the specified position.
―xxxx‖)
ListboxName.Items.RemoveAt(index) Removes an item, based on its index.
ListboxName.Items.Clear() Removes all the items in the list box.
Searches the given string the items collection, and returns the
ListboxName.Items.IndexOf(―xxxx‖)
index, if it is found; otherwise, it returns -1.
Design
label1:
Name: lblSelectCourse
Text: Select your Course:
label3:
listBox1: Name: lblSelectedCourse
Name: lstCourses Text: Selected Course Here
Items: .NET 4.0
Java label4:
Share Point Name: lblSelectedCourseIndexPrompt
Oracle DBA Text: Selected Course Index:
Sql Server label5:
QTP Name: lblSelectedCourseIndex
MS BI Text: Selected Course Index Here
label2:
Name: lblSelectedCoursePrompt
Text: Selected Course:
Design
groupBox1:
Name: grpCities
Text: Cities:
listBox1: button1:
Name: lstCities Name: btnAdd
Items: Hyderabad Text: Add
Pune
New Delhi button2:
Banglore Name: btnRemoveCity
Dehradun Items: Remove Selected City
groupBox2: button3:
Name: grpOptions Name: btnClearAll
Text: Options: Text: Clear All
label1: button4:
Name: lblNewCity Name: btnShowCount
Text: New City Name: Text: Show Count
textBox1:
Name: txtNewCity
label1:
11) ComboBox
API: System.Windows.Forms.ComboBox
Naming Convension: cmbxxxxxx
Properties of ComboBox
Property Description
Items Contains the list of items that can be displayed in the list box.
Simple: It looks like a text box, but the items can be accessed by pressing up / down
arrow keys.
DropDownStyle DropDown: It is the default value. The user can type new text (or) can select the
items from the list.
DropDownList: The user can type new text. Only selection is possible.
Sorted Enables / disables automatic sorting of items
Name, Text, TextAlign, BackColor, ForeColor, Font, Enabled, Visible, Size, Location, ContextMenuStrip
Events of ComboBox
Event Description
SelectedIndexChanged, TextChanged, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave,
KeyPress, Leave
Design
label1:
Name: lblSeleCourse
Text: Select Course:
comboBox1:
Name: cmbCourse
DropDownStyle: DropDownList
Items: .NET
Java
C
C++
Oracle
label2:
Name: lblFee
Text: Fee:
textBox1:
Name: txtFee
ReadOnly: True
12) NumericUpDown
This offers to enter a numerical value, within a given range. The user can enter a
value, out of the range.
API: System.Windows.Forms.NumericUpDown
Naming Convension: numxxxxxx
Properties of NumericUpDown
Property Description
Value Gets or sets the current value in the NumericUpDown control.
DecimalPlaces Specifies the no. of decimal places in the value
Minimum Specifies the minimum value in the range.
Maximum Specifies the maximum value in the range.
TextAlign Left / Center / Right
UpDownAlign Left / Right
Name, ReadOnly, BackColor, ForeColor, Font, Enabled, Visible, Size, Location, BackgroundImage,
BackgroundImageLayout, ContextMenuStrip, BorderStyle
Events of NumericUpDown
Event Description
ValueChanged, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave
API: System.Windows.Forms.DomainUpDown
Naming Convension: domxxxxxx
Properties of DomainUpDown
Property
Items, Sorted, Name, Text, TextAlign, BackColor, ForeColor, Font, Enabled, Visible, Size, Location,
ContextMenuStrip
Events of DomainUpDown
Event
SelectedItemChanged, TextChanged, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave,
KeyPress, Leave
Methods of DomainUpDown
Method
domObj.Items.Add(―xxxxx‖) Adds a new item at the end of the domainupdown items.
domObj.Items.Insert(index, ―xxxx‖) Inserts a new item at the specified position.
domObj.Items.RemoveAt(index) Removes an item, based on its index.
domObj.Items.Clear() Removes all the items in the domainupdown.
Searches the given string the items collection, and returns the
domObj.Items.IndexOf(―xxxx‖)
index, if it is found; otherwise, it returns -1.
domObj.Clear() Clears the text entered in the domainupdown.
14) DateTimePicker
API: System.Windows.Forms.DateTimePicker
Naming Convension: dtPickerxxxxxx
Properties of DateTimePicker
Property Description
Value Gets or sets the current value in the control.
Format Specifies the format of the date selection. (Short / Long / Time / Custom)
Used to specify the customer date formats. (with words and symbols like dd,
CustomFormat
mm, yyyy, -, / etc.)
ShowUpDown Enables / Disables the ―up/down‖ buttons in the control.
MinDate Specifies the minimum date, which can be selected at run time.
MaxDate Specifies the maximum date, which can be selected at run time.
Name, BackColor, ForeColor, Font, Enabled, Visible, Size, Location, ContextMenuStrip
Events of DateTimePicker
Event
ValueChanged, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave
15) MonthCalendar
API: System.Windows.Forms.MonthCalendar
Naming Convension: monCalxxxxxx
Events of MonthCalendar
Event Description
DateChanged, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave
Note: There is not any property, which gets the currently selected date in the calendar; so that,
we have to use ―DateRangeEventArgs‖ class object to access currently selected date value in the
―DateChanged‖ event.
API: System.Windows.Forms.TrackBar
Naming Convension: trkxxxxxx
Properties of TrackBar
Property Description
Value Gets or sets the current value in the control.
Minimum Specifies the minimum value in the range.
Maximum Specifies the maximum value in the range.
TickFrequency Specifies the difference between each tick.
Orientation Horizontal / Vertical
TickStyle None, TopLeft, BottomRight, Both
Name, BackColor, ForeColor, Enabled, Visible, Size, Location, ContextMenuStrip, BorderStyle
Events of TrackBar
Event Description
Scroll, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave
17) Timer
API: System.Windows.Forms.Timer
Naming Convension: tmrxxxxxx
Properties of Timer
Property Description
Interval Specifies the interval time of the timer, in the form of mille seconds.
Name, Enabled
Events of Timer
Event
Tick Executes on every completion of interval time.
Design
timer1:
Name: tmrBackColor
Interval: 500
Enabled: True
18) ProgressBar
API: System.Windows.Forms.ProgressBar
Naming Convension: prgxxxxxx
Properties of ProgressBar
Property Description
Value Gets or sets the current value in the control.
Minimum Specifies the minimum value in the range.
Maximum Specifies the maximum value in the range.
Name, BackColor, ForeColor, Enabled, Visible, Size, Location, ContextMenuStrip, BackgroundImage,
BackgroundImageLayout
Events of ProgressBar
Event Description
Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave
Design
label1:
Name: lblFileName
Text: Enter File Name:
textBox1:
Name: txtFileName textBox2:
Name: txtContent
button1: ReadOnly: True
Name: btnOpen WordWrap: False
Text: Open Multiline: True
label2: Scrollbars: Both
Name: lblLoading timer1:
Text: Loading… Name: tmrFileOpen
ForeColor: Red Enabled: False
Visible: False Interval: 100
progressBar1:
Name: prgFile
Visible: False
using System.IO;
19) MenuStrip
API: System.Windows.Forms.MenuStrip
Naming Convension: mnuxxxxxx
Properties of MenuStrip
Property Description
Dock Top, Bottom, Left, Right, Fill
TextDirection Horizontal, Vertial90, Vertical270.
Name, BackColor, ForeColor, Font, Enabled, Visible, Size, Location, BackgroundImage,
BackgroundImageLayout, ContextMenuStrip
Events of MenuStrip
Event Description
ItemClicked, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave
20) ContextMenuStrip
It is also a menu related control, similar to MenuStrip. But the context
menu would be displayed, when the user right
clicks on a control or a form, at run time. This is
also a collection of menu items. The context
menu is also called as ―Shortcut menu‖. The ―ContextMenuStrip‖ is an
invisible control.
API: System.Windows.Forms.ContextMenuStrip
Naming Convension: conMnuxxxxxx
Properties of ContextMenuStrip
Property Description
Name, BackColor, Font, Enabled, Size, Location, BackgroundImage, BackgroundImageLayout,
ContextMenuStrip
Events of ContextMenuStrip
Event Description
ItemClicked, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave
Note: All the dialog box controls are known as ―invisible controls‖.
21) ColorDialog
API: System.Windows.Forms.ColorDialog
Naming Convension: colorDlgxxxxxx
Design
button1:
Name: btnBackColor
Text: Back Color
colorDialog1:
Name: colorDlgBackColor
22) FontDialog
Displays a dialog box, for a font selection (with font name, bold, italic, regular, underline, font
size options).
API: System.Windows.Forms.FontDialog
Naming Convension: fontDlgxxxxxx
Design
textBox1:
Name: txtMyText
button1:
Name: btnFont
Text: Font
fontDialog1:
Name: fontDialogMyText
23) FolderBrowserDialog
API: System.Windows.Forms.FolderBrowserDialog
Naming Convension: folderBrowserDlgxxxxxx
Design
button1:
Name: btnBrowseFolder
Text: Browse Folder…
label1:
Name: lblSelectedFolder
Text: Selected Folder:
label2:
Name: lblFiles
Text: Files:
label3:
Name: lblSubFolders
Text: Sub Folders:
listBox1:
Name: lstFiles
listBox2:
Name: lstSubFolders
24) OpenFileDialog
API: System.Windows.Forms.OpenFileDialog
Naming Convension: openFileDlgxxxxxx
25) SaveFileDialog
API: System.Windows.Forms.SaveFileDialog
Naming Convension: saveFileDlgxxxxxx
26) PrintDialog
Displays a dialog box, for printing preferences selection like no. of copies, name of the printer,
paper range and paper orientation etc.
API: System.Windows.Forms.PrintDialog
Naming Convension: printDlgxxxxxx
Design
label1:
Name: lblFileName
Text: Enter File Name:
textBox1:
Name: txtFileName
button1:
Name: btnBrowse
Text: Browse...
button2:
Name: btnPrint
Text: Print
using System.Drawing.Printing;
using System.IO;
27) RichTextBox
A rich textbox is used for development of text editor applications like word pad, edit plus
etc.
It offers better features, when compared with the standard textbox.
It supports built-in file interaction with ―.rtf‖ files. (rtf stands for Rich Text Format).
One of the highlights of rich textbox is, to support different fonts and colors for part of
the text.
API: System.Windows.Forms.RichTextBox
Naming Convension: rtbxxxxxx
Methods of RichTextBox
Property Description
Clear() Clears entire text of the control.
Cut() Cuts the selected text.
Copy() Copies the selected text.
Paste() Pastes the text from the clipboard.
SelectAll() Selects the entire text in the control.
LoadFile(―rtf file path‖) Loads the text from the specified ―.rtf‖ file.
SaveFile(―rtf file path‖) Saves the text of the control, into ―.rtf‖ file.
Undo() Undos the previous action.
Redo() Redos the previous action.
Creates an icon at the system‘s notification area (on the windows task bar).
API: System.Windows.Forms.NotifyIcon
Naming Convension: notifyxxxxxx
Design
notifyIcon1:
Name: notifyIcon1
Text: My Application
Icon: laptop.ico
API: System.Windows.Forms.TabControl
Naming Convension: tbCtrlxxxxxx
Properties of TabControl
Property Description
TabPages Contains the list of tab pages.
Alignment Top, Bottom, Left, Right
Name, BackColor, ForeColor, Enabled, Visible, Size, Location, ContextMenuStrip, BackgroundImage,
BackgroundImageLayout
Events of TabControl
Event Description
SelectedIndexChanged, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter,
Leave
tabPage2:
Text: Choose Action
tabPage3:
Text: Get Result
label1:
Name: lblFirstValue
Text: Enter First Value:
label2:
Name: lblSecondValue
Text: Enter Second Value:
textBox1:
Name: txtFirstValue
textBox2:
Name: txtSecondValue
button1:
Name: btnAdd
Text: +
button2:
Name: btnMultiply
Text: *
label3:
Name: lblResult
Text: Result:
textBox3:
Name: txtResult
ReadOnly: True
30) TreeView
API: System.Windows.Forms.TreeView
Naming Convension: treexxxxxx
Properties of TreeView
Property Description
Nodes Contains the list of nodes.
ShowLines Displays / hides the lines in the tree view.
ShowPlusMinus Enables / disables the plus and minus symbols.
Name, BackColor, ForeColor, Enabled, Visible, Size, Location, ContextMenuStrip, BorderStyle
Events of TreeView
Event Description
AfterSelect, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave
Design
treeView1:
Name: treeMyTree
Nodes: (as shown right side)
button1:
Name: btnExpandAll
Text: Expand All
button2:
Name: btnCollapseAll
Text: Collapse All
label1:
Name: lblSelectedNode
Text: Selected Node:
label2:
Name: lblSelectedNodePath
Text: Selected Node Path:
MDI Applications
The windows applications are of two types.
1) SDI Applications (Single Document Interface)
2) MDI Applications (Multiple Document Interface)
1) All the child forms are contained by the parent form, so that the parent form is also
called as ―Container form‖.
2) Among several child forms, only one form acts as ―active child form‖.
3) Generally the parent form contains no UI design, it contains a menu.
4) Any child form can‘t be moved outside of its parent form.
5) In VB 6.0, only one form can be implemented as parent form in a project. But in C#.NET
and VB.NET, you can define multiple parent forms within the same project.
6) In VB 6.0, the parent form can‘t contain any type of controls. But in C#.NET and VB.NET,
you can drag any controls.
7) The child form icon is not displayed in the windows taskbar.
8) If the parent form is moved, all the child forms will be moved.
9) Whenever the parent form is minimized, all the child forms will be minimized.
10) Whenever the parent form is maximized, all the child forms will be restored.
11) Whenever the child form is minimized, an icon will be created at the bottom area of the
parent form.
12) Whenever the child form is maximized, the text of the parent form and child form will be
concatenated.
13) Whenever you close the parent form, all the child forms will be closed automatically.
14) The child form is able to access the reference of its parent form.
15) The parent form is able to access the references of its child forms.
Design
Form1:
IsMdiContainer: True
Form1.cs
Library: System.Windows.Forms.MessageBox
Syntax:
MessageBox.Show(“message”); MessageBox.Show(“message”,
MessageBoxButtons.xxxxxx);
1) MessageBoxButtons.OK
2) MessageBoxButtons.OKCancel
3) MessageBoxButtons.YesNo
4) MessageBoxButtons.YesNoCancel
5) MessageBoxButtons.RetryCancel
6) MessageBoxButtons.AbortRetryIgnore
Ex: MessageBox.Show(“Do you want to save the file?”, “My App 1.0”,
MessageBoxButtons.YesNo);
Sometimes, you may need to add the controls programmatically at run time.
obj.property = value;
containername.Add(value);
Design
button1:
Text: Add Exit Button
Output:
Design
button1:
Name: btnShowNumbers
Text: Show Numbers
textBox1:
ReadOnly: True
TextAlign: Right
Output:
Library: System.Drawings.Graphics
This class object is able to write any graphics on its container. That means every graphic object
requires a container. The container may be either form or panel.
Implementation:
In the above code, the ―CreateGraphics()‖ method creates a graphics object, that is able to write
the GDI graphics in the container (form).
1) Drawing Lines
g.DrawLine(Pens.xxxx, x1, y1, x2, y2);
4) Drawing Polygons
Point[] p = new Point[count];
p[0] = new Point(x,y);
p[1] = new Point(x,y);
p[2] = new Point(x,y);
……………………..
g.DrawPolygon(Pens.xxx, p);
5) Drawing Curves
Point[] p = new Point[count];
p[0] = new Point(x,y);
p[1] = new Point(x,y);
p[2] = new Point(x,y);
……………………..
g.DrawCurve(Pens.xxx, p);
Application 132: Demo on GDI (Drawing Lines, Rectangles, Circles, Triangles, Curves)
Click on ―Save‖ button to save the table. Then it asks for the table name. Enter
the desired table name.
6. Workingwith“Querywindow”:
―Query window‖ is a window, where you can enter the SQL queries and execute
them.
Open the ―Query window‖, by clicking on ―New Query‖ window option in the
toolbar.
Select the database from the database list, in which your query is to be
executed.
Enter the required SQL query in the window.
To execute, press ―F5‖ (or) click on ―Execute‖ button in the toolbar.
2. DROP
drop table tablename;
3. ALTER
alter table tablename add columnname datatype(width);
alter table tablename drop column columnname;
DML:
1. SELECT
select * from tablename;
select column1, column2, .. from tablename;
select * from tablename where condition;
select column1, column2, … from tablename where condition;
2. INSERT
insert into tablename values(value1, value2,…);
3. DELETE
delete from tablename;
delete from tablename where condition;
4. UPDATE
update tablename set column1=value1, column2=value2;
update tablename set column1=value1, column2=value2 where
condition;
use master
drop database test
GO
use test
GO
select * from Products where price not between 2000 and 8000
Functions:
create function functionname(@variable datatype(width),…)
returns returndatatype
as begin
declare @variable datatype(width)
…….
…….
return returnvalue
end
Note: The procedure can’t return any value; and a function should return any value. For every
variable in T-SQL, we have to prefix “@” symbol without fail.
Procedure:
GO
execute ShowSquare 5
Function:
GO
select dbo.GetCube(5)
Note: Here, the driver acts as mediator between the frontend application and backend
databases. The driver can also be called as ―Provider‖. This provider may be released by Backend
Company or Frontend Company.
Note: Just for separation of the individual values, we are using ―;‖.
ADO.NET Library
To perform above mentioned database operations, ADO.NET technology offers some pre-
defined classes, organized in the form of namespaces.
Library: System.Data
DataSet
DataTable
DataRow
DataColumn
SqlClient OleDb
SqlConnection OleDbConnection
SqlCommand OleDbCommand
SqlDataReader OleDbDataReader
SqlDataAdapter OleDbDataAdapter
SqlParameter OleDbParameter
ADO.NET NameSpaces:
1) System.Data
Contains necessary classes and namespaces to manipulate the databases.
2) System.Data.SqlClient
Contains necessary classes, used to interact with the SQL Server database.
3) System.Data.OleDb
Contains necessary classes, used to interact with any other databases. Of course,
the OleDb namespace also supports to connect with SQL server database, but
we won‘t use it for SQL Server, because ―SqlClient‖ namespace is especially
available for that.
1) Connection:
Maintains the connection with the database.
2) Command:
Executes a query statement (select statement), non-query statement (insert
statement / delete statement / update statement) or a stored procedure /
function at backend.
3) DataReader:
It acts as a buffer, which holds the data, after execution of a query statement at
backend.
4) DataAdapter:
Executes a query statement at backend.
5) Parameter:
Sends a parameter (argument) value to a backend stored procedure / function.
6) DataSet:
Acts as a buffer, which holds multiple tables at-a-time.
7) DataTable:
Acts as a buffer, which holds a single table (collection of rows and columns).
8) DataRow:
Acts as a buffer, which holds a single row.
9) DataColumn:
Acts as a buffer, which holds a single column.
Note: All of above are the classes; you need to create object(s) for those classes.
Connection
ConnectionString
Open()
Close()
ConnectionString: This property contains the connection string, used for the
connection.
Open(): This method opens the database connection.
Close(): This method disconnects the database connection.
1) Insertion Command:
To insert a new row into the table.
SQL statement: insert into tablename values(value1, value2,…)
2) Deletion Command:
To delete one or more rows from the table.
SQL statement: delete from tablename where condition
3) Updation Command:
To update (modify) the table data.
SQL statement: update tablename set column1=value1, column2=value2
where condition
4) Select Command:
To retrieve the data from the database table, into the frontend application.
SQL statement: select * from tablename
Connection Command
ConnectionString CommandText
Open() Connection
Close() CommandType
Parameters
ExecuteNonQuery()
ExecuteReader()
c) CommandType: This property specifies the type of the command that you want
to execute. It is of two types:
Text: (default) This is used for any SQL statement (insertion statement /
deletion statement / updation statement / select statement)
StoredProcedure: This is used for Stored Procedure / Function only.
Form1.cs