Sie sind auf Seite 1von 163

Welcome to the 5

th
Version Code-Kings Ebook for July
2013. This Ebook contains C# Codes and Examples to clear
your C# concepts and improve your programming skills.

A Simple Hello World Program Transpose a Matrix
Simple Calculator Named Arguments in C#
Drawing with Mouse on a Form Reverse Words in a String
Fetch Data from SQL Table Caller Information in C#
Insert & Retrieve from DB Convert Decimal to Binary
Autocomplete Feature Typing Game in C#
Random Generator Class Indexers
Class Inheritance Check Anagrams
Properties Create Controls at Runtime
Polymorphism Write to Windows Registry
Embed & Execute Resources Read From Windows Registry
Custom Settings Upcasting & Downcasting
Right Click Menu Enumerations
Data Binding in C# Read Files in Stream Reader
Send an Email in C# Creating Threads
Stream Writer: Write Files Create a Web Browser
DGV Filter & Expressions Draw Bitmap on Screen
Matrix Multiplication Identify Key Pressed
Strings: Selection Property Display Files & Folders
Linear & Binary Search Printing a Windows Form
Monitor On/Off/Stand By Show & Invert RGB Colors
Obtain Local Host IP Solve Quadratic Equation
Fibonacci Series Measure Date Difference
The Code-Kings Ebook (July 2013)
2 | Page
www.Code-Kings.com
Hello World Program in C#

This is a small program which shows the basic functionality of
C#. The program contains 2 labels. The labels are shown to
blink alternatively with the help of two timers. Whenever a
timer is enabled, the other timer is relaxed and a label linked
with the corresponding timer has its visible property set to true
while the other label has its visible property set to false. This
simple logic gives us the effect of alternative blinking of the
labels. You can set the tick property of the timer to a suitable
number. This gives the time in milliseconds between the blinks.
A word of caution : do not simply copy paste codes written here
instead type it in your IDE. For example to type in the code for
the first timer timer1 , double click on the timer1 which gives
you a fraction of code ready to begin with and then type in the
code within the closed block of curly braces.



using System;

namespace Hello_World
{
public partial class FrmHelloWorld : Form
{
The Code-Kings Ebook (July 2013)
3 | Page
www.Code-Kings.com
public FrmHelloWorld()
{
InitializeComponent();
}

private void timer1_Tick(object sender, EventArgs e)
{
lblWorld.visible = false;
lblHello.Visible = true;
timer1.Enabled = false;
timer2.Enabled = true;
}

private void timer2_Tick(object sender, EventArgs e)
{
lblHello.Visible = false;
lblWorld.Visible = true;
timer2.Enabled = false;
timer1.Enabled = true;
}

private void cmdClickHere_Click(object sender, EventArgs e)
{
if (cmdClickHere.Text = "Click Here !")
{
timer1.Enabled = true;
cmdClickHere.Text = "STOP !";
}
else
if (cmdClickHere.Text = "STOP !")
{
timer1.Enabled = false;
timer2.Enabled = false;
cmdClickHere.Text = "Click Here !";
}
}
}
}



The Code-Kings Ebook (July 2013)
4 | Page
www.Code-Kings.com



















The Code-Kings Ebook (July 2013)
5 | Page
www.Code-Kings.com
An Advanced Calculator

The .Net Framework provides a Math class with a loads of
mathematical functions like Sin, Cos, Tan, ASin, ACos, ATan,
Floor, Ceiling, Power, Log, Ln etc. We can easily use them by
simply referring to the Math functions. These Math class
functions take suitable parameters and return appropriate
datatypes which can be easily changed to Strings or Doubles.
The conversion here done is with the help of Convert class.



This is just another basic piece of code which illustrates a
different approach to the simple calculator which we use daily.
The calculator is designed to do 7 basic calculations like +,-
,*,/,sin,cos,tan. Of course there is no limit to the ways in which
we can combine these and create even more complex formulas.
The Code-Kings Ebook (July 2013)
6 | Page
www.Code-Kings.com
The calci stores different calculations in different textboxes ,
also showing the operand/s . This is simply achieved by
concatenating the operands retrieved from textboxes with the
appropriate operation sign in between and then appending the
calculated result in the end after an = sign. A word of caution :
C# asks programmers to be strict with the datatypes so we have
to convert and match existing datatypes to perform operations
especially mathematical. In other words we cannot apply the *
operation on two strings , instead we have to convert the strings
to integers and then apply the operation. This is simply achieved
by using the function Convert.ToInt32() which converts its
parameter into a 32 bit integer value(using 16 instead of 32
would convert it to a 16 bit integer value which also has a
smaller range as compared to 32 bit).

using System;

namespace Advanced_Calculator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Addition_Click(object sender, EventArgs e)
{
txtAddition.Text = txtX.Text + " + " + txtY.Text + " =
" + Convert.ToString(Convert.ToInt32((Convert.ToInt32(txtX.Text))+(Convert.ToInt
32(txtY.Text))));
}

private void Subtraction_Click(object sender, EventArgs e)
{
The Code-Kings Ebook (July 2013)
7 | Page
www.Code-Kings.com
txtSubtraction.Text = txtX.Text + " - " + txtY.Text + " =
" + Convert.ToString(Convert.ToInt32((Convert.ToInt32(txtX.Text)) -
(Convert.ToInt32(txtY.Text))));

}

private void Multiplication_Click(object sender, EventArgs e)
{
txtMultiplication.Text = txtX.Text + " * " + txtY.Text + " =
" + Convert.ToString(Convert.ToInt32((Convert.ToInt32(txtX.Text)) *
(Convert.ToInt32(txtY.Text))));

}

private void Division_Click(object sender, EventArgs e)
{
txtDivision.Text = txtX.Text + " / " + txtY.Text + " =
" + Convert.ToString(Convert.ToInt32((Convert.ToInt32(txtX.Text)) /
(Convert.ToInt32(txtY.Text))));

}

private void SinX_Click(object sender, EventArgs e)
{
txtSinX.Text = " Sin " +txtX.Text + " =
" + Convert.ToString(Math.Sin(Convert.ToDouble(txtX.Text)));
}

private void CosX_Click(object sender, EventArgs e)
{
txtCosX.Text = " Cos " + txtX.Text + " =
" + Convert.ToString(Math.Cos(Convert.ToDouble(txtX.Text)));
}

private void TanX_Click(object sender, EventArgs e)
{
txtTanX.Text = " Tan " + txtX.Text + " =
" + Convert.ToString(Math.Tan(Convert.ToDouble(txtX.Text)));
}
}
}
The Code-Kings Ebook (July 2013)
8 | Page
www.Code-Kings.com
Drawing with Mouse

This C# Windows Forms tutorial is a bit advanced program
which shows a glimpse of how we can use the graphics object
in C#. Our aim is to create a form and paint over it with the help
of the mouse just as a 'Pencil'. Very similar to the 'Pencil' in MS
Paint. We start off by creating a graphics object which is the
form in this case.

A graphics object provides us a surface area to draw to. We
draw small ellipses which appear as dots. These dots are
produced frequently as long as the left mouse button is pressed.
When the mouse is dragged, the dots are drawn over the path of
the mouse. This is achieved with the help of the MouseMove
event which means the dragging of the mouse. We simply write
code to draw ellipses each time a MouseMove event is fired.

Also on right clicking the Form, the background color is
changed to a random color. This is achieved by picking a
random value for Red, Blue and Green through the random
class. The Random object gives us a random integer value to
feed the Red, Blue & Green values of Color.FromArgb()
function(Which are between 0 and 255 for a 32 bit color
interface).
The Code-Kings Ebook (July 2013)
9 | Page
www.Code-Kings.com



The argument e gives us the source for identifying the button
pressed which in this case is desired to
be MouseButtons.Right i.e. the Right Mouse Button. The
Graphics Surface used to draw the Ellipse is the Form itself
which is referenced by the this keyword. The CreateGraphics()
Method is used to transform any Control on the Form or the
Form itself to a drawing surface and return it to the Graphics()
Object on the left of the assignment operator. We have drawn
small ellipses on the Form of size 5 pixels in Width and Height
using the Pen named p. Whenever we have pressed a Color
button, the Color property of the Pen p is changed to a required
color. This Pen is then passed as the parameter when drawing
the Ellipses.

The Code-Kings Ebook (July 2013)
10 | Page
www.Code-Kings.com

using System;
using System.Drawing;
using System.Windows.Forms;

namespace Mouse_Paint
{
public partial class MainForm : Form
{

public MainForm()
{
InitializeComponent();
}

private Graphics m_objGraphics;
Random rd = new Random();
Pen p = new Pen(Color.Black);

private void MainForm_Load(object sender, EventArgs e)
{
m_objGraphics = this.CreateGraphics();
}
private void MainForm_Close(object sender, EventArgs e)
{
m_objGraphics.Dispose();
}
private void MainForm_Click(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)

m_objGraphics.Clear(Color.FromArgb(rd.Next(0,255),rd.Next(0,255
),rd.Next(0,255)));
}

private void MainForm_MouseMove(object sender, MouseEventArg
s e)
{
Rectangle rectEllipse = new Rectangle();
if (e.Button != MouseButtons.Left) return;
The Code-Kings Ebook (July 2013)
11 | Page
www.Code-Kings.com
rectEllipse.X = e.X - 1;
rectEllipse.Y = e.Y - 1;
rectEllipse.Width = 5;
rectEllipse.Height = 5;
m_objGraphics.DrawEllipse(p, rectEllipse);

}

private void btnPurple_Click(object sender, EventArgs e)
{
p.Color = Color.Purple;
}

private void btnBlue_Click(object sender, EventArgs e)
{
p.Color = Color.Blue;
}

private void btnTurquoise_Click(object sender, EventArgs e)
{
p.Color = Color.Turquoise;
}

private void btnGreen_Click(object sender, EventArgs e)
{
p.Color = Color.Green;
}

private void btnYellow_Click(object sender, EventArgs e)
{
p.Color = Color.Yellow;
}

private void btnOrange_Click(object sender, EventArgs e)
{
p.Color = Color.Orange;
}
}
}

The Code-Kings Ebook (July 2013)
12 | Page
www.Code-Kings.com





















The Code-Kings Ebook (July 2013)
13 | Page
www.Code-Kings.com
Fetch Data from a Table

Fetching data from a table in C Sharp is quite easy. It First of all
requires creating a connection to the database in the form of a
connection string that provides an interface to the database with
our development environment. We create a temporary
DataTable for storing the database records for faster retrieval as
retrieving from the database time and again could have an
adverse effect on the performance. To move contents of the SQL
database in the DataTable we need a DataAdapter. Filling of the
table is performed by the Fill() function. Finally the contents of
DataTable can be accessed by using a double indexed object in
which the first index points to the row number and the second
index points to the column number starting with 0 as the first
index. So, if you have 3 rows in your table then they would be
indexed by row numbers 0 , 1 & 2.




using System;
using System.Data.SqlClient;

The Code-Kings Ebook (July 2013)
14 | Page
www.Code-Kings.com
namespace Data_Fetch_In_Table.Net
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

SqlConnection con = new SqlConnection(@"Data
Source=.\SQLEXPRESS;
AttachDbFilename= + Application.StartupPath.ToString() +
\\Database1.mdf; Integrated Security=True; User Instance=True");

SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand();
DataTable dt = new DataTable();

private void Form1_Load(object sender, EventArgs e)
{

SqlDataAdapter adapter = new SqlDataAdapter("select
* from Table1",con);

adapter.SelectCommand.Connection.ConnectionString
= @"Data
Source=.\SQLEXPRESS;
AttachDbFilename= + Application.StartupPath.ToString() +
"\\Database1.mdf;Integrated Security=True;
User Instance=True");
con.Open();

adapter.Fill(dt);

con.Close();
}

private void button1_Click(object sender, EventArgs e)
{

Int16 x = Convert.ToInt16(textBox1.Text);
The Code-Kings Ebook (July 2013)
15 | Page
www.Code-Kings.com

Int16 y = Convert.ToInt16(textBox2.Text);

string current =dt.Rows[x][y].ToString();

MessageBox.Show(current);

}
}
}































The Code-Kings Ebook (July 2013)
16 | Page
www.Code-Kings.com
Insert and Retrieve from Service Based Database

Now, we go a bit deeper in the SQL database in C# as we learn
how to Insert as well as Retrieve a record from a Database. Start
off by creating a Service Based Database which accompanies
the default created form named form1. Click Next until finished.
A Dataset should be automatically created. Next double click on
the Database1.mdf file in the solution explorer (Ctrl + Alt + L)
and carefully select the connection string. Format it in the way
as shown below by adding the @ sign and removing a couple of
"=" signs in between. The connection string in .Net Framework
4.0 does not need the removal of @ & "=" signs. The String is
generated perfectly ready to use. This step only applies to .Net
Framework 1.0 & 2.0.




There are two things left to be done now. One to insert & then to
Retrieve. We create an SQL command in the standard SQL
The Code-Kings Ebook (July 2013)
17 | Page
www.Code-Kings.com
Query format. Therefore, inserting is done by the SQL
command:
Insert Into <TableName> (Col1, Col2....) Values (Value for
Col1, Value for Col2....).

Execution of the Command/SQL Query is done by calling the
function ExecuteNonQuery(). The execution of a command
Triggers the SQL query on the outside and makes permanent
changes to the Database. Make sure your connection to the
database is open before you execute the query and also that you
close the connection after your query finishes.

To Retrieve the data from Table1 , we insert the present values
of the table into a DataTable from which we can retrieve & use
in our program easily. This is done with the help of a
DataAdapter. We fill our temporary DataTable with the help of
the Fill(TableName) function of the DataAdapter which fills a
DataTable with values corresponding to the select command
provided to it. The select command used here to retreive all the
data from the table is:
Select * From <TableName>

To retreive specific columns use:
Select Column1, Column2 From <TableName>.

Hints:
1. The Numbering of Rows Starts from an Index Value of 0
(Zero)
2. The Numbering of Columns also starts from an Index Value
of 0 (Zero)
3. To learn how to Filter the Column Values Please Read Here
The Code-Kings Ebook (July 2013)
18 | Page
www.Code-Kings.com
4. When working with SQL Databases use
the System.Data.SqlClient namespace
5. Try to create and work with low number of DataTables by
simply creating them common for all functions on a form.
6. Try NOT to create a DataTable every-time you are working
on a new function on the same form because then you will
have to carefully dispose it off.
7. Try to generate the Connection String dynamically by using
the Application.StartupPath.ToString() function
so that when the Database is situated on another
computer the path referred is correct.
8. You can also give a folder or file select dialog box for the
user to choose the exact location of the Database which
would prove flawless.
9. Try instilling Datatype constraints when creating your
Database. You can also implement constraints on your
forms(like NOT allowing user to enter alphabets in a
number field) but this method would provide a double
check & would prove flawless to the integrity of the
Database.
using System;
using System.Data.SqlClient;

namespace Insert_Show
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

The Code-Kings Ebook (July 2013)
19 | Page
www.Code-Kings.com
SqlConnection con = new SqlConnection(@"Data
Source=.\SQLEXPRESS;AttachDbFilename="+
+ Application.StartupPath.ToString()
+ "\\Database1.mdf;Integrated Security=True;
User Instance=True");

private void Form1_Load(object sender, EventArgs e)
{
MessageBox.Show("Click on Insert Button & then on
Show");
}

private void btnInsert_Click(object sender, EventArgs e
)
{
SqlCommand cmd = new SqlCommand("INSERT INTO Table1
(fld1, fld2, fld3) VALUES ("
+ "'I '" + "," + "' LOVE '" + "," + "' code-
kings.blogspot.com'" + ")", con);

con.Open();
cmd.ExecuteNonQuery();
con.Close();
}

private void btnShow_Click(object sender, EventArgs e)
{
DataTable table = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter("Select *
from Table1", con);
con.Open();
adp.Fill(table);
MessageBox.Show(table.Rows[0][0] + " " +
table.Rows[0][1] + " " +
table.Rows[0][2]);
}
}
}



The Code-Kings Ebook (July 2013)
20 | Page
www.Code-Kings.com
Autocomplete Feature in C#

This is a very useful feature for any graphical user interface
which makes it easy for users to fill in applications or forms by
suggesting them suitable words or phrases in appropriate text
boxes. So, while it may look like a tough job; its actually quite
easy to use this feature. The text boxes in C Sharp contain an
AutoCompleteMode which can be set to one of the three
available choices i.e. Suggest , Append or SuggestAppend. Any
choice would do but my favourite is the SuggestAppend. In
SuggestAppend, Partial entries make intelligent guesses if the
So Far typed prefix exists in the list items. Next we must set
the AutoCompleteSource to CustomSource as we will supply
the words or phrases to be suggested through a suitable data
source. The last step includes calling the
AutoCompleteCustomSouce.Add() function with the required.
This function can be used at runtime to add list items in the box.

The Code-Kings Ebook (July 2013)
21 | Page
www.Code-Kings.com



using System;

namespace Auto_Complete_Feature_in_C_Sharp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
textBox2.AutoCompleteMode
= AutoCompleteMode.SuggestAppend;

textBox2.AutoCompleteSource
= AutoCompleteSource.CustomSource;

The Code-Kings Ebook (July 2013)
22 | Page
www.Code-Kings.com
textBox2.AutoCompleteCustomSource.Add("code-
kings.blogspot.com");
}

private void button1_Click(object sender, EventArgs e)
{

textBox2.AutoCompleteCustomSource.Add(textBox1.Text.ToString())
;

textBox1.Clear();
}
}
}









The Code-Kings Ebook (July 2013)
23 | Page
www.Code-Kings.com
Random Generator Class in C#

The C Sharp language has a good support for creating random
entities such as integers, bytes or doubles. First we need to
create the Random Object. The next step is to call the Next()
function in which we may supply a minimum and maximum
value for the random integer. In our case we have set the
minimum to 1 and maximum to 9. So, each time we click the
button we have a set of random values in the three labels. Next,
we check for the equivalence of the three values; and if they are
then we append two zeroes to the text value of the label thereby
increasing the value 100 times. Finally we use the
MessageBox() to show the amount of money won.





using System;

The Code-Kings Ebook (July 2013)
24 | Page
www.Code-Kings.com
namespace Playing_with_the_Random_Class
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

Random rd = new Random();

private void button1_Click(object sender, EventArgs e)
{
label1.Text = Convert.ToString(rd.Next(1, 9));
label2.Text = Convert.ToString(rd.Next(1, 9));
label3.Text = Convert.ToString(rd.Next(1, 9));

if (label1.Text == label2.Text && label1.Text ==
label3.Text)
{
MessageBox.Show("U HAVE WON " + "$ " +
label1.Text+"00"+ " !!");
}
else
{
MessageBox.Show("Better Luck Next Time");
}
}

}
}


The Code-Kings Ebook (July 2013)
25 | Page
www.Code-Kings.com








The Code-Kings Ebook (July 2013)
26 | Page
www.Code-Kings.com
Class Inheritance in C#

Classes can inherit from other classes. They can gain
Public/Protected Variables and Functions of the parent class.
The class then acts as a detailed version of the original parent
class(also known as the base class). The code below shows the
simplest of examples :

public class A
{
//Define Parent Class
public A() { }
}

public class B : A
{
//Define Child Class
public B() { }
}

In the following program we shall learn how to create &
implement Base and Derived Classes. First we create a
BaseClass and define the Constructor , SHoW & a function to
square a given number. Next , we create a derived class and
define once again the Constructor , SHoW & a function to Cube
a given number but with the same name as that in the BaseClass.
The code below shows how to create a derived class and inherit
the functions of the BaseClass. Calling a function usually calls
the DerivedClass version. But it is possible to call the BaseClass
version of the function as well by prefixing the function with the
BaseClass name.

class BaseClass
{
public BaseClass()
{
Console.WriteLine("BaseClass Constructor
Called\n");
The Code-Kings Ebook (July 2013)
27 | Page
www.Code-Kings.com
}

public void Function()
{
Console.WriteLine("BaseClass Function Called\n
Enter A Single No.");
int number = new int();
number = Convert.ToInt32(Console.ReadLine());
number = number * number;
Console.WriteLine("Square is : " + number + "\n");
}

public void SHoW()
{
Console.WriteLine("Inside the BaseClass\n");
}
}



class DerivedClass : BaseClass
{
public DerivedClass()
{
Console.WriteLine("DerivedClass Constructor
Called\n");
}

public new void Function()
{
Console.WriteLine("DerivedClass Function Called\n
Enter A Single No.");
int number = new int();
number = Convert.ToInt32(Console.ReadLine());
number = Convert.ToInt32(number)
* Convert.ToInt32(number)
*Convert.ToInt32(number) ;
Console.WriteLine("Cube is : " + number + "\n");
}

public new void SHoW()
The Code-Kings Ebook (July 2013)
28 | Page
www.Code-Kings.com
{
Console.WriteLine("Inside the DerivedClass\n");
}
}


class Program
{
static void Main(string[] args)
{
DerivedClass dr = new DerivedClass();

dr.Function(); //Call DerivedClass Function

((BaseClass)dr).Function(); //Call BaseClass
Version

dr.SHoW(); //Call DerivedClass SHoW

((BaseClass)dr).SHoW(); //Call BaseClass Version

Console.ReadKey();
}
}

The Code-Kings Ebook (July 2013)
29 | Page
www.Code-Kings.com
Properties in C#

Properties are used to encapsulate the state of an object in a
class. This is done by creating Read Only, Write Only or Read
Write properties. Traditionally, methods were used to do this.
But now the same can be done smoothly & efficiently with the
help of properties.

A property with Get() can be read & a property with Set() can be
written. Using both Get() & Set() make a property Read-Write.
A property usually manipulates a private variable of the class.
This variable stores the value of the property. A benefit here is
that minor changes to the variable inside the class can be
effectively managed. For example, if we have earlier set an ID
property to integer and at a later stage we find that alphanumeric
characters are to be supported as well then we can very quickly
change the private variable to a string type.

using System;
using System.Collections.Generic;
using System.Text;

namespace CreateProperties
{
class Properties
{
//Please note that variables are declared private
//which is a better choice vs declaring them as public

private int p_id = -1;

public int ID
{
get
{
return p_id;
The Code-Kings Ebook (July 2013)
30 | Page
www.Code-Kings.com
}
set
{
p_id = value;
}
}

private string m_name = string.Empty;

public string Name
{
get
{
return m_name;
}
set
{
m_name = value;
}
}

private string m_Purpose = string.Empty;

public string P_Name
{
get
{
return m_Purpose;
}
set
{
m_Purpose = value;
}
}
}
}


using System;

namespace CreateProperties
The Code-Kings Ebook (July 2013)
31 | Page
www.Code-Kings.com
{
class Program
{
static void Main(string[] args)
{
Properties object1 = new Properties();

//Set All Properties One by One
object1.ID = 1;
object1.Name = "www.code-kings.blogspot.com";
object1.P_Name = "Teach C#";

Console.WriteLine("ID " + object1.ID.ToString());

Console.WriteLine("\nName " + object1.Name);

Console.WriteLine("\nPurpose " + object1.P_Name);

Console.ReadKey();
}
}
}



The Code-Kings Ebook (July 2013)
32 | Page
www.Code-Kings.com
Also, properties can be used without defining a a variable to
work with in the beginning. We can simply use get & set
without using the return keyword i.e. without explicitly referring
to another previously declared variable. These are Auto-
Implement properties. The get & set keywords are immediately
written after declaration of the variable in brackets. Thus, the
property name & variable name are the same.

using System;
using System.Collections.Generic;
using System.Text;

public class School
{
public int No_Of_Students{ get; set; }
public string Teacher{ get; set; }
public string Student{ get; set; }
public string Accountant{ get; set; }
public string Manager{ get; set; }
public string Principal{ get; set; }
}

















The Code-Kings Ebook (July 2013)
33 | Page
www.Code-Kings.com
Polymorphism in C#

Polymorphism is one of the primary concepts of Object Oriented
Programming. There are basically two types of polymorphism
(i) RunTime (ii) CompileTime. Overriding a virtual method
from a parent class in a child class is RunTime polymorphism
while CompileTime polymorphism consists of overloading
identical functions with different signatures in the same class.
This program depicts Run Time Polymorphism.


The method Calculate(int x) is first defined as a virtual function
int he parent class & later redefined with the override keyword.
Therefore, when the function is called, the override version of
the method is used.

The example below shows the how we can implement
polymorphism in C Sharp. There is a base class
called PolyClass. This class has a virtual
function Calculate(int x) . The function exists only
virtually i.e. it has no real existence. The function is meant to
redefined once again in each subclass. The redefined function
gives accuracy in defining the behavior intended. Thus, the
accuracy is achieved on a lower level of abstraction. The four
subclasses namely : CalSquare, CalSqRoot, CalCube
& CalCubeRoot give a different meaning to the same named
function Calculate(int x). When we initialize objects of the base
class, we specify the type of object to be created.

namespace Polymorphism
{
public class PolyClass
{
The Code-Kings Ebook (July 2013)
34 | Page
www.Code-Kings.com
public virtual void Calculate(int x)
{
Console.WriteLine("Square Or Cube ?? Which One
??");
}
}

public class CalSquare : PolyClass
{
public override void Calculate(int x)
{
Console.WriteLine("Square : ");
//Calculate the Square of a number

Console.WriteLine(Convert.ToString(Convert.ToInt64(
x * x ) ));
}
}

public class CalSqRoot : PolyClass
{
public override void Calculate(int x)
{
Console.WriteLine("Square Root Is : ");
//Calculate the Square Root of a number

Console.WriteLine(Convert.ToString(Convert.ToInt64(
Math.Sqrt( x))));
}
}

public class CalCube : PolyClass
{
public override void Calculate(int x)
{
Console.WriteLine("Cube Is : ");
//Calculate the cube of a number

Console.WriteLine(Convert.ToString(Convert.ToInt64(
x * x * x)));
}
The Code-Kings Ebook (July 2013)
35 | Page
www.Code-Kings.com
}

public class CalCubeRoot : PolyClass
{
public override void Calculate(int x)
{
Console.WriteLine("Cube Square Is : ");

//Calculate the Cube Root of a number

Console.WriteLine(Convert.ToString(Convert.ToInt64(
Math.Pow(x,
(0.3333333333333)))));
}
}

}


namespace Polymorphism
{
class Program
{
static void Main(string[] args)
{
PolyClass[] CalObj = new PolyClass[4];
int x;
CalObj[0] = new CalSquare();
CalObj[1] = new CalSqRoot();
CalObj[2] = new CalCube();
CalObj[3] = new CalCubeRoot();

foreach (PolyClass CalculateObj in CalObj)
{
Console.WriteLine("Enter Integer");
x = Convert.ToInt32(Console.ReadLine());
CalculateObj.Calculate( x );

}
Console.WriteLine("Aurevoir !");
Console.ReadKey();
The Code-Kings Ebook (July 2013)
36 | Page
www.Code-Kings.com
}
}
}























The Code-Kings Ebook (July 2013)
37 | Page
www.Code-Kings.com
Embed and Execute Resource Files

We shall now learn how to embed files internally into a
program. The file can be any type i.e. with any extension. The
fun part is that the file's visibility to the user can be controlled &
can also be moved to any location within the hard disk. Thus we
can execute exe's on a completely different process/thread. If we
have programs that were built before & need reuse or desired to
be run parallel, this is the technique.The process is explained as
follows:


1. Right click on the project name and select Properties.

2. Click on the Resources tab on the Left.

3. Click on Add Resource >> Add Existing File.

4. Choose the file location on your HDD & u will see the file
available in the Solution Explorer.

5. You will be able to access this file using a funtion shown
below:

string exePath
= Application.StartupPath.ToString()+"\\FileName.exe";

public void ExtractResource(string resource)
{
Stream stream =
GetType().Assembly.GetManifestResourceStream(resource);
byte[] bytes = new byte[(int)stream.Length];
stream.Read(bytes, 0, bytes.Length);
File.WriteAllBytes(exePath, bytes);
System.Diagnostics.Process.Start(exePath);
The Code-Kings Ebook (July 2013)
38 | Page
www.Code-Kings.com
}

Use this function as explained

*Call the ExtractResource() function whenever you want to run
an embedded resource file.

*The string 'resource' is the exact file name including the
extension(.exe, .txt, etc).

*The string 'path' is where the resource will be extracted before
it is run. The resource will be extracted only when
needed/called.

*If the File is not an exe then the default program will be used to
launch the file.

*The above function actually extracts the resource in the
execution path/folder itself(the value of exePath). The value can
be anything suitable or even custom. The selection can be made
by the choose folder dialog box.

*The System.Diagnostics.Process.Start(exePath) function
executes an executable file from HDD whose location is given
in the parameter.











The Code-Kings Ebook (July 2013)
39 | Page
www.Code-Kings.com
Save Custom User Settings and Preferences

Your C# application settings allow you to store and retrieve
custom property settings and other information for your
application. These properties and settings can be manipulated at
runtime using:

ProjectNameSpace.Settings.Default.PropertyName

The .NET Framework allows you to create and access values
that are persisted between application execution sessions. These
settings can represent user preferences, or valuable information
the application needs to use or should have. For example, you
might create a series of settings that store user preferences for
the color scheme of an application. Or you might store a
connection string that specifies a database that your application
uses. Please note that whenever you create a new Database, C#
automatically creates the connection string as a default setting.


Settings allow you to both persist information that is critical to
the application outside of the code, and to create profiles that
store the preferences of individual users. They make sure that no
two copies of an application look exactly the same & also that
users can style the application GUI as they want.

To create a setting :

*Right Click on the project name in the explorer window; Select
Properties

*Select the settings tab on the left
The Code-Kings Ebook (July 2013)
40 | Page
www.Code-Kings.com

*Select the name & type of the setting that required

*Set default values in the value column


Suppose the namespace of the project is ProjectNameSpace &
property is PropertyName.

To modify the setting at runtime and subsequently save it :

ProjectNameSpace.Settings.Default.PropertyName =
DesiredValue;

ProjectNameSpace.Properties.Settings.Default.Save();

The synchronize button overrides any previously saved setting
with the ones specified on the page.
















The Code-Kings Ebook (July 2013)
41 | Page
www.Code-Kings.com
Right Click Menu in C#

Best known as the Context Menu Strip in .Net Framework, it
provides a convenient way to create the Right Click menu. Start
off by dragging the tool named ContextMenuStrip in the
Toolbox window, under the Menus & Toolbars tab. Works just
like the Menu tool, Add & Delete items as you desire. Items
include Textbox, Combobox or yet another Menu Item.


For displaying the Menu, we have to simply check if the
right mouse button was pressed. This can be done easily by
creating the MouseClick event in the form's Designer.cs file.
The MouseEventArgs contains a check to see if the right
mouse button was pressed(or left, middle etc.).

The Show() method is a little tricky to use. When using this
method, the first parameter is the location of the button relative
to the X & Y coordinates that we supply next(the second & third
arguments). The best method is to place an invisible control at
the location (0,0) in the form. Then, the arguments to be passed
are the e.X & e.Y in the Show() method. In short :

ContextMenuStrip.Show(UnusedControl,e.X,e.Y);

The Code-Kings Ebook (July 2013)
42 | Page
www.Code-Kings.com

The Code-Kings Ebook (July 2013)
43 | Page
www.Code-Kings.com





The Code-Kings Ebook (July 2013)
44 | Page
www.Code-Kings.com














The Code-Kings Ebook (July 2013)
45 | Page
www.Code-Kings.com
Data Binding in C#

Data Binding is indispensable for a programmer. It allows
data(or a group) to change when it is bound to another data item.
The Binding concept uses the fact that attributes in a table have
some relation to each other. When the value of one field
changes, the changes should be effectively seen in the other
fields. This is similar to the Look-up function in Microsoft
Excel. Imagine having multiple text boxes whose value depend
on a key field. This key field may be present in another text box.
Now, if a value in the Key field changes, the change must be
reflected in all other text boxes.


In C Sharp(Dot Net), combo boxes can be used to place key
field/s. Working with combo boxes is much easier compared to
text boxes. We can easily bind field/s in a data table created in
SQL by merely setting some properties in a combo box. Combo
box has three main fields that have to be set to effectively add
contents of a data field(Column) to the domain of values in the
combo box. We shall also learn how to bind data to text boxes
from a data source.
First set the Data Source property to the existing data
source which could be a dynamically created data table or
could be a link to an existing SQL table as we shall see.

Set the Display Member property to the column that you
want to display from the table.

The Code-Kings Ebook (July 2013)
46 | Page
www.Code-Kings.com
Set the Value Member property to the column that you
want to choose the value from.
Consider a table shown below:








The Item Number is the key and the Item Value DEPENDS on
it. The aim of this program is to create a DataTable during run-
time & display the columns in two combo boxes.The following
example shows a two-way dependency i.e. if the value of any
combo box changes, the change must be reflected in the other
combo box. Two-way updates the target property or the source
property whenever either the target property or the source
property changes.The source property changes first then triggers
an update in the Target property. In Two-way updates either
field may act as a Trigger or a Target. To illustrate this, we
simply write the code in the Load event of the form. The code is
shown below:


namespace Use_Data_Binding
{
public partial class Form1 : Form
The Code-Kings Ebook (July 2013)
47 | Page
www.Code-Kings.com
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
//Create The Data Table
DataTable dt = new DataTable();

//Set Columns
dt.Columns.Add("Item Number");
dt.Columns.Add("Item Name");

//Add Rows/Records
dt.Rows.Add("1", "T.V.");
dt.Rows.Add("2","Fridge");
dt.Rows.Add("3","Phone");
dt.Rows.Add("4", "Laptop");
dt.Rows.Add("5", "Speakers");

//Set Data Source Property
comboBox1.DataSource = dt;
comboBox2.DataSource = dt;

//Set Combobox 1 Properties
comboBox1.ValueMember = "Item Number";
comboBox1.DisplayMember = "Item Number";

//Set Combobox 2 Properties
comboBox2.ValueMember = "Item Number";
comboBox2.DisplayMember = "Item Name";
}
}
}


The Code-Kings Ebook (July 2013)
48 | Page
www.Code-Kings.com














The Code-Kings Ebook (July 2013)
49 | Page
www.Code-Kings.com
Send an Email in C#

The .Net Framework has fantastic support for web applications.
The System.Net.Mail can be used to send Emails very easily.
All you require is a valid Username & Password that you use to
log into your email account. Attachments of various file types
like PNG and JPEG can be very easily attached with the body of
the mail. Below is a function shown to send an email if you are
sending through a gmail account. The default port number is 587
& is checked to work well in all conditions.


The MailMessage class contains everything you'll need to
send an email. The information related to an email
like From, To, Subject, CC, BCC etc. These parameters can be
set to the Object created from the MailMessage Class. Also
note that the attachment object has a text parameter. This text
parameter is actually the file path of the file that is to be sent as
the attachment. When you click the attach button, a file path
dialog box appears which allows us to choose the file path(of an
existing file) on your Hard Disk.

public void SendEmail()
{
try
{
MailMessage mailObject = new MailMessage();
SmtpClient SmtpServer
= new SmtpClient("smtp.gmail.com");
mailObject.From
= new MailAddress(txtFrom.Text);
mailObject.To.Add(txtTo.Text);
mailObject.Subject = txtSubject.Text;
mailObject.Body = txtBody.Text;

The Code-Kings Ebook (July 2013)
50 | Page
www.Code-Kings.com
if (txtAttach.Text != "") // Check if
Attachment Exists
{

System.Net.Mail.Attachment attachmentObject;
attachmentObject
= new System.Net.Mail.Attachment(txtAttach.Text);

mailObject.Attachments.Add(attachmentObject);
}

SmtpServer.Port = 587;
SmtpServer.Credentials
= new System.Net.NetworkCredential(txtFrom.Text,
txtPassKey.Text);
SmtpServer.EnableSsl = true;

SmtpServer.Send(mailObject);
MessageBox.Show("Mail Sent Successfully");
}
catch (Exception ex)
{
MessageBox.Show("Some Error Plz Try
Again", "http://www.code-kings.blogspot.com");
}
}

The Code-Kings Ebook (July 2013)
51 | Page
www.Code-Kings.com

















The Code-Kings Ebook (July 2013)
52 | Page
www.Code-Kings.com
Stream Writer in C#

The StreamWriter is used to write data to the hard disk. The
data may be in the form of Strings, Characters, Bytes etc. Also
you can specify he type of encoding that you are using. The
Constructor of the StreamWriter class takes basically two
arguments: The first one is the actual file path with file name
that you want to write & the second one specifies if you would
like to replace or overwrite an existing
file.The StreamWriter creates objects that have interface with
the actual files on the hard disk and enable them to be written to
text or binary files. In this example we write a text file to the
hard disk whose location is chosen through a save file dialog
box.


The file path can be easily chosen with the help of a save file
dialog box(SFD). If the file already exists the default mode will
be to append the lines to the existing content of the file. The data
type of lines to be written can be specified in the parameter
supplied to the Write or Write method of the StreaWriter object.
Therefore the Write method can have arguments of type Char,
Char[], Boolean, Decimal, Double, Int32, Int64, Object, Single,
String, UInt32, UInt64.


using System;

namespace StreamWriter
{
public partial class Form1 : Form
{
public Form1()
{
The Code-Kings Ebook (July 2013)
53 | Page
www.Code-Kings.com
InitializeComponent();
}

private void btnChoosePath_Click(object sender, EventAr
gs e)
{
if (SFD.ShowDialog() ==
System.Windows.Forms.DialogResult.OK)
{
txtFilePath.Text = SFD.FileName;

txtFilePath.Text += ".txt";
}
}

private void btnSaveFile_Click(object sender, EventArgs
e)
{
System.IO.StreamWriter objFile =
new System.IO.StreamWriter(txtFilePath.Text,true);

for (int i = 0; i < txtContents.Lines.Length; i++)
{

objFile.WriteLine(txtContents.Lines[i].ToString());
}

objFile.Close();

MessageBox.Show("Total Number of Lines Written :
" +
txtContents.Lines.Length.ToString());
}

private void Form1_Load(object sender, EventArgs e)
{
// Anything
}
}
}

The Code-Kings Ebook (July 2013)
54 | Page
www.Code-Kings.com





















The Code-Kings Ebook (July 2013)
55 | Page
www.Code-Kings.com
DataGridView Filter and Expressions

Often we need to filter a DataGridView in our database
programs. The C# datagrid is the best tool for database display
& modification. There is an easy shortcut to filtering a
DataTable in C# for the DataGridView. This is done by simply
applying an expression to the required column. The expression
contains the value of the filter to be applied. The filtered
DataTable must be then set as the DataSource of the
DataGridView.




In this program we have a simple DataTable containing a total
of 5 columns: Item Name, Item Price, Item Quantity, Item Tax
& Item Total. This DataTable is then displayed in the C#
datagrid. The fourth & fifth columns have to be calculated as a
multiplied value(by multiplying 2nd and 3rd columns).

We simply add rows with values set for three columns. We let
the Tax & Total columns get calculated automatically through
the Expression value of the Columns. The application of
expressions is simple, just type what you want it to be! For
The Code-Kings Ebook (July 2013)
56 | Page
www.Code-Kings.com
example, if you want the 10% Tax Column to generate values
automatically, you can set the Column.Expression as:

"<Column1> = <Column2> * <Column3> * 0.1"

where the Columns are Tax, Price & Quantity respectively. Note
a hint here: the columns are specified as a decimal type and 0.1
means precisely 10%.

Finally after all rows have been set, we can apply appropriate
filters on the columns in the C# datagrid control. This is
accomplished by setting the filter value in one of the three
TextBoxes & clicking the corresponding filter button. The Filter
expressions are calculated by simply picking up the values from
the validating TextBoxes & matching them to their Column
name.

Note that the text changes dynamically on the Button. The Text
property allows you to easily preview a filter value. In this way
we achieve the TextBox validation.

namespace Filter_a_DataGridView
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

DataTable dt = new DataTable(); // Form Table that
Persists

//throughout and its structure and Column values never
change

The Code-Kings Ebook (July 2013)
57 | Page
www.Code-Kings.com
//once you click the "Show Table with Tax & Amount"
Button

private void Form1_Load(object sender, EventArgs e)
{
DataColumn Item_Name = new DataColumn("Item_Name", // Define
Type.GetType("System.String")); //
DataColumn Item_Price = new DataColumn("Item_Price", // the input
Type.GetType("System.Decimal")); //
DataColumn Item_Qty = new DataColumn("Item_Qty", // Columns
Type.GetType("System.Decimal"));

DataColumn Item_Tax = new DataColumn("Item_tax", // Define Tax
Type.GetType("System.Decimal"));
// "Item_Tax" column is calculated (10% Tax)
Item_Tax.Expression = "Item_Price * Item_Qty * 0.1";

DataColumn Item_Total = new DataColumn("Item_Total", // Define Total
Type.GetType("System.Decimal"));
// "Item_Total" column is calculated as (Price * Qty + Tax)
Item_Total.Expression = "Item_Price * Item_Qty +
Item_Tax";

dt.Columns.Add(Item_Name); // Add 4
dt.Columns.Add(Item_Price); // Columns
dt.Columns.Add(Item_Qty); // to
dt.Columns.Add(Item_Tax); // the
dt.Columns.Add(Item_Total); // Datatable
}

private void btnInsert_Click(object sender, EventArgs e)
{
dt.Rows.Add(txtItemName.Text, txtItemPrice.Text, txtItemQty.Text);

MessageBox.Show("Row Inserted");
}

private void btnShowFinalTable_Click(object sender, EventArgs e)
{
this.Height = 637; // Extend

dgv.DataSource = dt;
btnShowFinalTable.Enabled = false;
}

private void btnPriceFilter_Click(object sender, EventArgs e)
{
// Creating a new table allows to preserve
//original data and work the filters on the new DataTable

DataTable NewDT = new DataTable(); //Create a new DataTable
NewDT = dt.Copy(); //Copy existing data
The Code-Kings Ebook (July 2013)
58 | Page
www.Code-Kings.com

//Apply Filter Value
NewDT.DefaultView.RowFilter = "Item_Price = ' " + txtPriceFilter.Text + " '
";

//Set new table as DataSource
dgv.DataSource = NewDT;
}

private void txtPriceFilter_TextChanged(object sender, EventArgs e)
{
// Change/Update Button Text Dynamically
btnPriceFilter.Text = "Filter DataGridView by Price : " +
txtPriceFilter.Text;
}

private void btnQtyFilter_Click(object sender, EventArgs e)
{
// Creating a new table allows to preserve
//original data and work the filters on the new DataTable

DataTable NewDT = new DataTable();
NewDT = dt.Copy();
NewDT.DefaultView.RowFilter = "Item_Qty = ' " + txtQtyFilter.Text + " ' ";
dgv.DataSource = NewDT;
}

private void txtQtyFilter_TextChanged(object sender, EventArgs e)
{
// Change/Update Button Text Dynamically
btnQtyFilter.Text = "Filter DataGridView by Total : " + txtQtyFilter.Text;
}

private void btnTotalFilter_Click(object sender, EventArgs e)
{
// Creating a new table allows to preserve
//original data and work the filters on the new DataTable

DataTable NewDT = new DataTable();
NewDT = dt.Copy();
NewDT.DefaultView.RowFilter = "Item_Total = ' " + txtTotalFilter.Text + " '
";
dgv.DataSource = NewDT;
}

private void txtTotalFilter_TextChanged(object sender, EventArgs e)
{
// Change/Update Button Text Dynamically
btnTotalFilter.Text = "Filter DataGridView by Total : " +
txtTotalFilter.Text;
}

private void btnFilterReset_Click(object sender, EventArgs e)
{
The Code-Kings Ebook (July 2013)
59 | Page
www.Code-Kings.com
DataTable NewDT = new DataTable();
NewDT = dt.Copy();
dgv.DataSource = NewDT;
}
}
}




The Code-Kings Ebook (July 2013)
60 | Page
www.Code-Kings.com











The Code-Kings Ebook (July 2013)
61 | Page
www.Code-Kings.com
Matrix Multiplication in C#

The Perfect Matrix Multiplication Programming Tutorial in a C#
Console Application.

Multiply any number of rows with any number of
columns
Check for Matrices with invalid rows and Columns
Ask for entry of valid Matrix elements if value entered is
invalid
All work done in .Net Framework 4.5
The code has a main class which consists of 3 functions
logically structured
The first function reads valid elements in the Matrix
Arrays
The second function multiplies matrices with the help of
for loop
The third function simply displays the resultant Matrix
Check for the source code at the end.

The Function ReadMatrix() basically reads the values of all
elements of the two matrices that are to be multiplied. Also,
prior to reading, the matrices are defined with their number of
rows and columns. Note that to multiply two matrices we need
the number of columns of first matrix to be equal to the number
of rows of second matrix. So, when we multiply Mat A x Mat B,
number of columns in A should be equal to number of rows in
B. Also note that A x B is not equal to B x A.

The Code-Kings Ebook (July 2013)
62 | Page
www.Code-Kings.com



public void ReadMatrix()
{
Console.WriteLine("**********************************************
******");
The Code-Kings Ebook (July 2013)
63 | Page
www.Code-Kings.com
Console.WriteLine("*********http://www.code-
kings.blogspot.com*********");
Console.WriteLine("**********************************************
******\n");
Console.WriteLine("\nPlease Enter Details of First Matrix");
Console.Write("\n*Number of Rows in First Matrix : ");
int m = int.Parse(Console.ReadLine());
Console.Write("\n*Number of Columns in First Matrix : ");
int n = int.Parse(Console.ReadLine());
a = new int[m, n];
Console.WriteLine("\n*Enter the elements of First Matrix : ");
for (int i = 0; i < a.GetLength(0); i++)
{
for (int j = 0; j < a.GetLength(1); j++)
{
try
{
Console.WriteLine("Enter Element " + (1 +
i).ToString() + " " + (1 + j).ToString());
a[i, j] = int.Parse(Console.ReadLine());
Console.WriteLine(" Value Accepted");
}
catch
{
try
{
Console.WriteLine("Enter Element " + (1 +
i).ToString() + " " + (1 + j).ToString());
Console.WriteLine("\nPlease Enter a Valid
Value");
a[i, j] = int.Parse(Console.ReadLine());
Console.WriteLine(" Value Accepted");
}
catch
{
Console.WriteLine("\nPlease Enter a Valid
Value(Final Chance)");
Console.WriteLine("Enter Element " + (1 +
i).ToString() + " " + (1 + j).ToString());
a[i, j] = int.Parse(Console.ReadLine());
Console.WriteLine(" Value Accepted");
}
}
}
}
Console.WriteLine("\nPlease Enter Details of Second Matrix");
Console.Write("\n**Number of Rows in Second Matrix :");
m = int.Parse(Console.ReadLine());
Console.Write("\n**Number of Columns in Second Matrix :");
n = int.Parse(Console.ReadLine());
The Code-Kings Ebook (July 2013)
64 | Page
www.Code-Kings.com
b = new int[m, n];
Console.WriteLine("\n**Please Enter Elements of Second Matrix:");
for (int i = 0; i < b.GetLength(0); i++)
{
for (int j = 0; j < b.GetLength(1); j++)
{
try
{
Console.WriteLine("Enter Element " + (1 +
i).ToString() + " " + (1 + j).ToString());
b[i, j] = int.Parse(Console.ReadLine());
Console.WriteLine(" Value Accepted");
}
catch
{
try
{
Console.WriteLine("\nPlease Enter a Valid
Value");
b[i, j] = int.Parse(Console.ReadLine());
Console.WriteLine(" Value Accepted");
}
catch
{
Console.WriteLine("\nPlease Enter a Valid
Value(Final Chance)");
b[i, j] = int.Parse(Console.ReadLine());
Console.WriteLine(" Value Accepted");
}
}
}
}
}

The function to print the first and second matrix followed by the
resultant matrix is shown below. A for loop embedded in
another for loop does this job very well. The first for loop works
for the row number while the second for loop works for the
column number.

public void PrintMatrix()
{
Console.WriteLine("\nFirst Matrix:");
for (int i = 0; i < a.GetLength(0); i++)
{
for (int j = 0; j < a.GetLength(1); j++)
The Code-Kings Ebook (July 2013)
65 | Page
www.Code-Kings.com
{
Console.Write("\t" + a[i, j]);
}
Console.WriteLine();
}
Console.WriteLine("\n Second Matrix:");
for (int i = 0; i < b.GetLength(0); i++)
{
for (int j = 0; j < b.GetLength(1); j++)
{
Console.Write("\t" + b[i, j]);
}
Console.WriteLine();
}
Console.WriteLine("\n Resultant Matrix by Multiplying First &
Second Matrix");
for (int i = 0; i < c.GetLength(0); i++)
{
for (int j = 0; j < c.GetLength(1); j++)
{
Console.Write("\t" + c[i, j]);
}
Console.WriteLine();
}

Console.WriteLine("Do You Want To Multiply Once Again (Y/N)");

if (Console.ReadLine().ToString()
== "y" || Console.ReadLine().ToString()
== "Y" || Console.ReadKey().ToString() == "y" || Console.ReadKey().ToString()
== "Y")
{
MatrixMultiplication mm = new MatrixMultiplication();
mm.ReadMatrix();
mm.MultiplyMatrix();
mm.PrintMatrix();
}
else
{
Console.WriteLine("\nMatrix Multiplication\n");
Console.ReadKey();
Environment.Exit(-1);
}
}

The logic for multiplying the two matrices is shown below in the
image:

The Code-Kings Ebook (July 2013)
66 | Page
www.Code-Kings.com


A row of the first Matrix and Column of the second Matrix are
taken. The corresponding terms are multiplied and added
together. They are stored in a location(Matrix C) that is
specified by the Row Number of Matrix A and Column Number
of Matrix B. The simplest way to do this in your code is by
adding a total of 3 for loops. The first two loops simulate the
Row Number and Column Number. The third for loop adds the
three multiplied pair elements together and stores their result in
the C Matrix. Watch the code below:

public void MultiplyMatrix()
{
if (a.GetLength(1) == b.GetLength(0))
{
c = new int[a.GetLength(0), b.GetLength(1)];
for (int i = 0; i < c.GetLength(0); i++)
{
The Code-Kings Ebook (July 2013)
67 | Page
www.Code-Kings.com
for (int j = 0; j < c.GetLength(1); j++)
{
c[i, j] = 0;
for (int k = 0; k < a.GetLength(1); k++)

// OR k<b.GetLength(0)

c[i, j] = c[i, j] + a[i, k] * b[k, j];
}
}
}
else
{
Console.WriteLine("\n Number of columns in First Matrix
should be equal to Number of rows in Second Matrix.");
Console.WriteLine("\n Please re-enter correct dimensions.");
Environment.Exit(-1);
}
}

























The Code-Kings Ebook (July 2013)
68 | Page
www.Code-Kings.com
Working with Strings: Selection Property

This Program in C# 5 shows the use of the Selection property of
the TextBox control. This property is accompanied with the
Select() function which must be used to reflect changes you
have set to the Selection properties. As you can see, the form
also contains two TrackBars. These TrackBars actually visualize
the Selection property attributes of the TextBox. There are two
Selection properties mainly: Selection Start & Selection Length.
These two properties are shown through the current value
marked on the TrackBar.




private void Form1_Load(object sender, EventArgs e)
{
// Set initial values
txtLength.Text = textBox.Text.Length.ToString();
trkBar1.Maximum = textBox.Text.Length;
}

private void trackBar1_Scroll(object sender, EventArgs
e)
{
The Code-Kings Ebook (July 2013)
69 | Page
www.Code-Kings.com
// Set the Max Value of second TrackBar
trkBar2.Maximum = textBox.Text.Length -
trkBar1.Value;

textBox.SelectionStart = trkBar1.Value;

txtSelStart.Text = trkBar1.Value.ToString();

textBox.SelectionLength = trkBar2.Value;

txtSelEnd.Text =
(trkBar1.Value + trkBar2.Value).ToString();

txtTotChars.Text = trkBar2.Value.ToString();

textBox.Select();
}


Let us understand the working of this property with a simple
String "ABCDEFGH". Suppose you wanted to select the
characters from between B & C and Between F & G ("A B C D
E F G H"), you would set the Selection Start to 2 and the
Selection Length to 4. As always, the index starts from 0(Zero)
therefore the Selection Start would be 0 if you wanted to start
before A i.e. include A as well in the selection.

The Code-Kings Ebook (July 2013)
70 | Page
www.Code-Kings.com


Notice something below: As we move to the right in the First
TrackBar (provided the length of the string remains the same),
We find that the second TrackBar has a lower range i.e. a
reduced Maximum value.


private void trackBar2_Scroll(object sender, EventArgs e)
{
textBox.SelectionStart = trkBar1.Value;

txtSelStart.Text = trkBar1.Value.ToString();

textBox.SelectionLength = trkBar2.Value;

txtSelEnd.Text =
(trkBar1.Value + trkBar2.Value).ToString();

txtTotChars.Text = trkBar2.Value.ToString();

textBox.Select();
}

The Code-Kings Ebook (July 2013)
71 | Page
www.Code-Kings.com


This is only logical. When we move on to the right, we have a
higher Selection Start value. Therefore the number of selected
characters possible will be lesser than before because the leading
characters will be left out from the Selection Start property.
Therefore its just showing graphically how many characters of
the String are showed on a Text Box on the Form.







The Code-Kings Ebook (July 2013)
72 | Page
www.Code-Kings.com
Searching Techniques: Linear & Binary

Searching is needed when we have a large array of some data or
objects & need to find the position of a particular element. We
may also need to check if an element exists in a list or not.
While there are built in functions that offer these capabilities,
they only work with predefined datatypes. Therefore there may
the need for a custom function that searches elements & finds
the position of elements. Below you will find two search
techniques viz. Linear Search & Binary Search implemented in
C#. The code is simple & easy to understand & can be modified
as per need.








Algorithms for Linear Search Technique in C#

The Code-Kings Ebook (July 2013)
73 | Page
www.Code-Kings.com

using System;
using System.Text;
using System.Threading.Tasks;

namespace Linear_Search
{
class Program
{
static void Main(string[] args)
{
Int16[] array = new Int16[100];
Int16 search, c, number;

Console.WriteLine("Enter the number of elements in array\n");
number = Convert.ToInt16(Console.ReadLine());

Console.WriteLine("Enter " + number.ToString() + " numbers\n");

for (c = 0; c < number; c++)
{
array[c] = new Int16();
array[c] = Convert.ToInt16(Console.ReadLine());
}

Console.WriteLine("Enter the number to search\n");
search = Convert.ToInt16(Console.ReadLine());

for (c = 0; c < number; c++)
{
if (array[c] == search) /* if required element found */
{
Console.WriteLine("" + search.ToString() + " is present at location " + (c +
1).ToString() +
".\n");
break;
}
}
if (c == number)
Console.WriteLine(search.ToString() + " is not present in array.\n");

Console.ReadLine();
}
}
}

The Code-Kings Ebook (July 2013)
74 | Page
www.Code-Kings.com
Binary Search Technique in C Sharp

using System;
using System.Text;
using System.Threading.Tasks;

namespace Binary_Search
{
class Program
{
static void Main(string[] args)
{
int c, first, last, middle, n, search;
Int16[] array = new Int16[100];

Console.WriteLine("Enter number of elements\n");
n = Convert.ToInt16(Console.ReadLine());

Console.WriteLine("Enter " + n.ToString() + " integers\n");

for (c = 0; c < n; c++)
{
array[c] = new Int16();
array[c] = Convert.ToInt16(Console.ReadLine());
}

Console.WriteLine("Enter value to find\n");
search = Convert.ToInt16(Console.ReadLine());

first = 0;
last = n - 1;
middle = (first + last) / 2;

while (first <= last)
{
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search)
{
Console.WriteLine(search + " found at location " + (middle + 1));
break;
}
else
last = middle - 1;

middle = (first + last) / 2;
The Code-Kings Ebook (July 2013)
75 | Page
www.Code-Kings.com
}
if (first > last)
Console.WriteLine("Not found! " + search + " is not present in the
list.");

Console.ReadKey();
}
}
}

































The Code-Kings Ebook (July 2013)
76 | Page
www.Code-Kings.com
Monitor Turn ON/OFF/Standby

You might want to change your display settings in a running
program. The code behind requires the Import of a Dll &
execution of a function SendMessage(,,,) by supplying 4
parameters. The value of the fourth parameter having values 0, 1
& 2 has the monitor in the states ON, STAND BY & OFF
respectively. The first parameter has the value of the valid
window which has received the handle to change the monitor
state. This must be an active window. You can see the simple
code below:




using System;

using System.Windows.Forms;

using System.Runtime.InteropServices;

namespace Turn_Off_Monitor

{

public partial class Form1 : Form

{

The Code-Kings Ebook (July 2013)
77 | Page
www.Code-Kings.com
public Form1() { InitializeComponent(); }

[DllImport("user32.dll")]

public static extern IntPtr SendMessage(IntPtr hWnd, ui
nt Msg,

IntPtr wParam, IntPtr lParam);

private void btnStandBy_Click(object sender, EventArgs
e)

{

IntPtr a = new IntPtr(1);

IntPtr b = new IntPtr(0xF170);

const int WM_SYSCOMMAND = 0x0112;

SendMessage(this.Handle, WM_SYSCOMMAND, b, a);

}

private void btnMonitorOff_Click(object sender, EventAr
gs e)

{

IntPtr a = new IntPtr(2);

IntPtr b = new IntPtr(0xF170);

const int WM_SYSCOMMAND = 0x0112;

SendMessage(this.Handle, WM_SYSCOMMAND, b,a);

}

private void btnMonitorOn_Click(object sender, EventArg
s e)
The Code-Kings Ebook (July 2013)
78 | Page
www.Code-Kings.com

{

IntPtr a = new IntPtr(-1);

IntPtr b = new IntPtr(0xF170);

const int WM_SYSCOMMAND = 0x0112;

SendMessage(this.Handle, WM_SYSCOMMAND, b, a);

}

}

}

























The Code-Kings Ebook (July 2013)
79 | Page
www.Code-Kings.com
Obtain IP Address of Machine

This program illustrates how we can obtain the IP address of
Local Host. If a string parameter is supllied in the exe then the
same is used as the local host name. If not then the local host
name is retrieved and used. See the code below:




using System;
using System.Net;

namespace Obtain_IP_Address_in_C_Sharp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("********************************
*****");
Console.WriteLine("*****www.code-
kings.blogspot.com*****");
Console.WriteLine("********************************
*****\n");

String StringHost;
The Code-Kings Ebook (July 2013)
80 | Page
www.Code-Kings.com

if (args.Length == 0)
{
// Getting Ip address of local machine...
// First get the host name of local machine.
StringHost = System.Net.Dns.GetHostName();
Console.WriteLine("Local Machine Host Name is:
" + StringHost);
Console.WriteLine("");
}
else
{
StringHost = args[0];
}

// Then using host name, get the IP address list..
IPHostEntry ipEntry =
System.Net.Dns.GetHostEntry(StringHost);

IPAddress[] address = ipEntry.AddressList;

for (int i = 0; i < address.Length; i++)
{
Console.WriteLine("");
Console.WriteLine("IP Address Type {0}: {1} ",
i, address[i].ToString());
}
Console.Read();
}
}
}










The Code-Kings Ebook (July 2013)
81 | Page
www.Code-Kings.com
Fibonacci Series C# Code

Fibonacci series is a series of numbers where the next number is
the sum of the previous two numbers behind it. It has the
starting two numbers predefined as 0 & 1. The series goes on
like this:
0,1,1,2,3,5,8,13,21,34,55,89,144,233,377..

Here we illustrate two techniques for the creation of the
Fibonacci Series to n terms. The For Loop method & the
Recursive Technique. Check them below.


The For Loop technique requires that we create some variables
and keep track of the latest two terms('First' & 'Second'). Then
we calculate the next term by adding these two terms & setting a
new set of two new terms. These terms are the 'Second' &
'Newest'.




The Code-Kings Ebook (July 2013)
82 | Page
www.Code-Kings.com
using System;
using System.Text;
using System.Threading.Tasks;

namespace Fibonacci_series_Using_For_Loop
{
class Program
{
static void Main(string[] args)
{
int n, first = 0, second = 1, next, c;
Console.WriteLine("Enter the number of terms");
n = Convert.ToInt16(Console.ReadLine());
Console.WriteLine("First "+ n +" terms of Fibonacci series
are:");
for (c = 0; c < n; c++)
{
if (c <= 1)
next = c;
else
{
next = first + second;
first = second;
second = next;
}
Console.WriteLine(next);
}
Console.ReadKey();
}
}
}

The recursive technique to a Fibonacci series requires the creation of a function that
returns an integer sum of two new numbers. The numbers are one & two less than the
number supplied. In this way final output value has each number added twice
excluding 0 & 1. Check the program below.

The Code-Kings Ebook (July 2013)
83 | Page
www.Code-Kings.com
using System;
using System.Text;
using System.Threading.Tasks;

namespace Fibonacci_Series_Recursion
{
class Program
{
static void Main(string[] args)
{
int n, i = 0, c;
Console.WriteLine("Enter the number of terms");
n=Convert.ToInt16(Console.ReadLine());
Console.WriteLine("First 5 terms of Fibonacci series
are");
for ( c = 1 ; c <= n ; c++ )
{
Console.WriteLine(Fibonacci(i));
i++;
}
Console.ReadKey();
}
static int Fibonacci(int n)
{
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return (Fibonacci(n - 1) + Fibonacci(n - 2));
}
}
}












The Code-Kings Ebook (July 2013)
84 | Page
www.Code-Kings.com
Transpose a Matrix

This program illustrates how to find the transpose of a given
matrix. Check code below for details.



using System;
using System.Text;
using System.Threading.Tasks;

namespace Transpose_a_Matrix
{
class Program
{
static void Main(string[] args)
{
int m, n, c, d;

int[,] matrix = new int[10, 10];

int[,] transpose = new int[10, 10];

Console.WriteLine("Enter the number of rows and columns of matrix ");

m = Convert.ToInt16(Console.ReadLine());

n = Convert.ToInt16(Console.ReadLine());

Console.WriteLine("Enter the elements of matrix \n");

The Code-Kings Ebook (July 2013)
85 | Page
www.Code-Kings.com
for (c = 0; c < m; c++)
{
for (d = 0; d < n; d++)
{
matrix[c, d] = Convert.ToInt16(Console.ReadLine());
}
}

for (c = 0; c < m; c++)
{
for (d = 0; d < n; d++)
{
transpose[d, c] = matrix[c, d];
}
}

Console.WriteLine("Transpose of entered matrix");

for (c = 0; c < n; c++)
{
for (d = 0; d < m; d++)
{
Console.Write(" " + transpose[c, d]);
} Console.WriteLine();
}

Console.ReadKey();

}
}
}















The Code-Kings Ebook (July 2013)
86 | Page
www.Code-Kings.com


Reverse Words in a String

This simple C# program reverses the words that reside in a
string. The words are assumed to be separated by a single space
character. The space character along with other consecutive
letters forms a single word. Check the program below for
details:





using System;

namespace Reverse_String_Test
{
class Program
{
public static string reverseIt(string strSource)
{
string[] arySource = strSource.Split(new char[] { '
' });
string strReverse = string.Empty;

for (int i = arySource.Length - 1; i >= 0; i--)
{
strReverse = strReverse + " " + arySource[i];
The Code-Kings Ebook (July 2013)
87 | Page
www.Code-Kings.com
}

Console.WriteLine("Original String: \n\n" +
strSource);

Console.WriteLine("\n\nReversed String: \n\n" +
strReverse);

return strReverse;
}

static void Main(string[] args)
{
reverseIt(" I Am In Love With www.code-
kings.blogspot.com.com");

Console.WriteLine("\nPress any key to
continue....");
Console.ReadKey();
}
}

}


















The Code-Kings Ebook (July 2013)
88 | Page
www.Code-Kings.com

Caller Information in C#

Caller Information is a new concept introduced in C# 5. It is
aimed at providing useful information about where a function
was called. It gives information such as:
Full path of the source file that contains the caller. This is
the file path at compile time.
Line number in the source file at which the method is
called.
Method or property name of the caller.
We specify the following(as optional parameters) attributes in
the function definition respectively:

[CallerMemberName] a String
[CallerFilePath] an Integer
[CallerLineNumber] a String
We use Trace.WriteLine() to output information in the trace
window.

here is a C# example:

public void TraceMessage(string message,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0)
{
Trace.WriteLine("message: " + message);
Trace.WriteLine("member name: " + memberName);
Trace.WriteLine("source file path: " +
sourceFilePath);
The Code-Kings Ebook (July 2013)
89 | Page
www.Code-Kings.com
Trace.WriteLine("source line number: " +
sourceLineNumber);
}

You can use the CallerMemberName in:

* Method, Property or Event: They return name of the method,
property, or event from which the call originated.

* Constructors: They return the String ".ctor"

* Static Constructors: They return the String ".cctor"

* Destructor: They return the String "Finalize"

* User Defined Operators or Conversions: They return generated
member name

Whenever we call the TraceMessage() method, it outputs the
required information as
stated above.

Note: Use only with optional parameters. Caller Info does not
work when you do not use optional parameters.











The Code-Kings Ebook (July 2013)
90 | Page
www.Code-Kings.com
Convert from Decimal to Binary

This code below shows how you can convert a given Decimal
number to the Binary number system. This is illustrated by using
the Binary Right Shift Operator ">>".



using System;
using System.Text;
using System.Threading.Tasks;

namespace convert_decimal_to_binary
{
class Program
{
static void Main(string[] args)
{
int n, c, k;
Console.WriteLine("Enter an integer in Decimal number
system\n");
n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\nBinary Equivalent is:\n");
for (c = 31; c >= 0; c--)
{
k = n >> c;
if (Convert.ToBoolean(k & 1))
Console.Write("1");
else
Console.Write("0");
}
Console.ReadKey();
}
}
}



The Code-Kings Ebook (July 2013)
91 | Page
www.Code-Kings.com
Typing Game in C#

This is a basic typing game concept. The form will display
random letters. If the player types one of them, it disappears and
the accuracy rate goes up. If the player types an incorrect letter,
the accuracy rate goes down. As the player keeps typing letters,
the game goes faster and faster, getting more difficult with each
correct letter. If the form fills up with letters, the game is over!






DIRECT DOWNLOAD CODE FOR THIS PROGRAM HERE

Set up the Timer control:
Did you notice how your Timer control didnt show up on your
form? Thats because the Timer is a non-visual control. It
doesnt actually change the look and feel of the form. It does
exactly one thing: it calls a method over and over again. Set the
Timer controls Interval property to 800, so that it calls its
The Code-Kings Ebook (July 2013)
92 | Page
www.Code-Kings.com
method every 800 milliseconds. Then double-click on the timer1
icon in the designer. The IDE will do what it always does when
you double-click on a control: it will add a method to your form.
This time, itll add one called timer1_Tick. Heres the code for
it:

private void timer1_Tick(object sender, EventArgs e)

{
// Add a random key to the ListBox
listBox1.Items.Add((Keys)random.Next(65, 90));
if (listBox1.Items.Count > 7)
{
listBox1.Items.Clear();
listBox1.Items.Add(Game over);
timer1.Stop();
}
}

Add a class to keep track of the player stats. If the form is going
to display the total number of keys the player pressed, the
number that were missed and the number that were correct, and
the players accuracy, then well need a way to keep track of all
that data. Sounds like a job for a new class! Add a class called
Stats to your project. Itll have four int fields called Total,
Missed, Correct, and Accuracy, and a method called Update
with one bool parameter: true if the player typed a correct letter
that was in the ListBox, or false if the player missed one.




Create Stats: Total Missed Correct Accuracy Update()

class Stats
{
public int Total = 0;
The Code-Kings Ebook (July 2013)
93 | Page
www.Code-Kings.com
public int Missed = 0;
public int Correct = 0;
public int Accuracy = 0;
public void Update(bool correctKey)
{
Total++;
if (!correctKey)
{
Missed++;
}
else
{
Correct++;
}
Accuracy = 100 * Correct / (Missed + Correct);
}
}

Add fields to your form to hold a Stats object and a Random
object. Youll need an instance of your new Stats class to
actually store the information, so add a field called stats to store
it. And you already saw that youll need a field called random
itll contain a Random object. Add the two fields to the top of
your form:

public partial class Form1 : Form
{
Random random = new Random();
Stats stats = new Stats();
...

Handle the keystrokes.
Theres one last thing your game needs to do: any time the
player hits a key, it needs to check if that key is correct (and
remove the letter from the ListBox if it is), and update the stats
on the StatusStrip. Go back to the form designer and select the
form. Then go to the Properties window and click on the
The Code-Kings Ebook (July 2013)
94 | Page
www.Code-Kings.com
lightning bolt button. Scroll to the KeyDown row and double-
click on it. This tells the IDE to add a method called
Form1_KeyDown() that gets called every time the user presses a
key. Heres the code for the method:

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
// If the user pressed a key that's in the ListBox, remove it
// and then make the game a little faster
if (listBox1.Items.Contains(e.KeyCode))
{
listBox1.Items.Remove(e.KeyCode);
listBox1.Refresh();
if (timer1.Interval > 400)
timer1.Interval -= 10;
if (timer1.Interval > 250)
timer1.Interval -= 7;
if (timer1.Interval > 100)
timer1.Interval -= 2;
difficultyProgressBar.Value = 800 - timer1.Interval;
// The user pressed a correct key, so update the Stats object
// by calling its Update() method with the argument true
stats.Update(true);
}
else
{
// The user pressed an incorrect key, so update the Stats
object
// by calling its Update() method with the argument false
stats.Update(false);
}
// Update the labels on the StatusStrip
correctLabel.Text = "Correct: " + stats.Correct;
missedLabel.Text = "Missed: " + stats.Missed;
totalLabel.Text = "Total: " + stats.Total;
accuracyLabel.Text = "Accuracy: " + stats.Accuracy + "%";
}

Run your game.
Your games done! Give it a shot and see how well you do. You
may need to adjust the font size of the ListBox to make sure it
The Code-Kings Ebook (July 2013)
95 | Page
www.Code-Kings.com
holds exactly 7 letters, and you can change the difficulty by
adjusting the values that
are subtracted from timer1.Interval in the Form1_KeyDown()
method.

DIRECT DOWNLOAD CODE FOR THIS PROGRAM HERE

































The Code-Kings Ebook (July 2013)
96 | Page
www.Code-Kings.com
Indexers in C#

Indexers are elements in a C# program that allow a Class to
behave as an Array. You would be able to use the entire class as
an array. In this array you can store any type of variables. The
variables are stored at a separate location but addressed by the
class name itself. Creating indexers for Integers, Strings,
Boolean etc. would be a feasible idea. These indexers would
effectively act on objects of the class.

Lets suppose you have created a class indexer that stores the roll
number of a student in a class. Further, lets suppose that you
have created an object of this class named obj1. When you
say obj1[0], you are referring to the first student on roll.
Likewise obj1[1] refers to the 2nd student on roll.

Therefore the object takes indexed values to refer to the Integer
variable that is privately or publicly stored in the class. Suppose
you did not have this facility then you would probably refer in
this way:
obj1.RollNumberVariable[0]
obj1.RollNumberVariable[1].
where RollNumberVariable would be the Integer variable.

Now that you have learnt how to index your class & learnt to
skip using variable names again and again, you can effectively
skip the variable name RollNumberVariable by indexing the
same.
Indexers are created by declaring their access specifier and
WITHOUT a return type. The type of variable that is stored in
The Code-Kings Ebook (July 2013)
97 | Page
www.Code-Kings.com
the Indexer is specified in the parameter type following the
name of the Indexer. Below is the program that shows how to
declare and use Indexers in a C# Console environment:

using System;

namespace Indexers_Example
{
class Indexers
{
private Int16[] RollNumberVariable;

public Indexers(Int16 size)
{
RollNumberVariable = new Int16[size];

for (int i = 0; i < size; i++)
{
RollNumberVariable[i] = 0;
}
}

public Int16 this[int pos]
{
get
{
return RollNumberVariable[pos];
}
set
{
RollNumberVariable[pos] = value;
}
}
}
}

using System;

namespace Indexers_Example
{
The Code-Kings Ebook (July 2013)
98 | Page
www.Code-Kings.com
class Program
{
static void Main(string[] args)
{
Int16 size = 5;

Indexers obj1 = new Indexers(size);

for (int i = 0; i < size; i++)
{
obj1[i] = (short)i;
}

Console.WriteLine("\nIndexer Output\n");

for (int i = 0; i < size; i++)
{
Console.WriteLine("Next Roll No: " + obj1[i]);
}

Console.Read();
}
}
}

Indexers can be overloaded as well. Give it a try!










The Code-Kings Ebook (July 2013)
99 | Page
www.Code-Kings.com
Anagram Test

This program shows how you can check if two given input
strings are Anagrams or not in CSharp language. Anagrams are
two different words or combinations of characters which have
the same alphabets and their counts. Therefore a particular set of
alphabets can create many permutations of Anagrams. In other
words, if we have the same set of characters in two
words(strings) then they are Anagrams.

We create a function that has input as a character array pair of
inputs. When we get the two different sets of characters, we
check the count of each alphabet in these two sets. Finally, we
tally and check if the value of character count for each alphabet
is the same or not in these sets. If all characters occur at the
same rate in both the sets of characters, then we declare the sets
to be Anagrams otherwise not.

See the code below in C#:

using System;

namespace Anagram_Test
{
class ClassCheckAnagram
{
public int check_anagram(char[] a, char[] b)
{
Int16[] first = new Int16[26];
Int16[] second = new Int16[26];
int c = 0;

for (c = 0; c < a.Length; c++)
{
first[a[c] - 'a']++;
}

The Code-Kings Ebook (July 2013)
100 | Page
www.Code-Kings.com
c = 0;

for (c=0; c<b.Length; c++)
{
second[b[c] - 'a']++;

}

for (c = 0; c < 26; c++)
{
if (first[c] != second[c])
return 0;
}

return 1;
}
}
}

namespace Anagram_Test
{
class Program
{
static void Main(string[] args)
{

ClassCheckAnagram cca = new ClassCheckAnagram();
Console.WriteLine("Enter first string\n");
string aa = Console.ReadLine();
char[] a = aa.ToCharArray();

Console.WriteLine("\nEnter second string\n");
string bb = Console.ReadLine();
char[] b = bb.ToCharArray();
int flag = cca.check_anagram(a, b);

if (flag == 1)
Console.WriteLine("\nThey are anagrams.\n");
else
Console.WriteLine("\nThey are not anagrams.\n");
Console.ReadKey();
}

}
}

The Code-Kings Ebook (July 2013)
101 | Page
www.Code-Kings.com
Create Controls at Runtime

Sometimes you might want to create a user control at run-time.
These are times when you are not sure of what controls to
include during the form designing phase of your program. What
we usually do is to draw all available controls in the designer
form. Then at run-time we simply make the controls invisible
leaving us with workable visible controls. But there is a better
method. What should be done is exactly illustrated below. You
should write code to draw the controls at run-time. You should
draw the controls when needed to save memory.



Creating controls at runtime can be very useful if you have some
conditions that you might want to satisfy before displaying a set
of controls. You might want to display different controls for
different situations. CSharp provides an easy process to create
them. If you look carefully in the Designer.cs file of any form,
you will find codes that initiate the creation of controls. You will
The Code-Kings Ebook (July 2013)
102 | Page
www.Code-Kings.com
see only some properties set, leaving other properties default.
And this is exactly what we will do here. We write code behind
the Form that creates the controls with some properties that we
set & others that are simply set to their default value by the
Compiler.

The main steps to draw controls are summarized below:
Create/Define the control or Array of controls
Set the properties of the control or individual controls
in case of Arrays
Add the control/s to the form or other parent containers
such as Panels
Call the Show() method to display the control

The code below shows how to draw controls:

namespace Create.Controls.At.Runtime
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
TextBox[] tb = new TextBox[7];
for (int i = 0; i <= 6; i++)
{
tb[i] = new TextBox();
tb[i].Width = 150;
tb[i].Left = 20;
tb[i].Top = (30 * i) + 30;
The Code-Kings Ebook (July 2013)
103 | Page
www.Code-Kings.com
tb[i].Text = "Text Box Number: " +
i.ToString();
this.Controls.Add(tb[i]);
tb[i].Show();
}
}
}
}




















The Code-Kings Ebook (July 2013)
104 | Page
www.Code-Kings.com
Writing Registry Values

Developing a real application almost everytime requires the
storing of some important values in the Windows Registry. The
Windows Registry gives the power to store variables of different
types by any application and use them as and when required.
You can also store values in the form of texts, external files or
saved documents then why use the Registry? Because the
Registry allows above all the values to be stored and read in a
standardized way which can be read by compatible applications
as and when required. Also, the deletion of corresponding files
does not alter the information in the Windows Registry. The
contents have to be modified explicitly to delete or modify
existing values.

The windows registry can be modified using the C#
programming interface. In this section we shall see how to write
to a known location in the windows registry. The Windows
registry consists of different locations in an explorer style and
looks as shown below:



The Code-Kings Ebook (July 2013)
105 | Page
www.Code-Kings.com
The Keys at the parent level
are HKEY_CLASSES_ROOT, HKEY_CURRENT_USER et
c. When we refer to these keys in our C# program code, we omit
the HKEY & the underscores. So, to refer to
the HKEY_CURRENT_USER, we use
simply CurrentUser as the reference. Well, this reference is
available from the Microsoft.Win32.Registry class. This
Registry class is available through the reference:
using Microsoft.Win32;
.We use this reference to create a Key object. An example of a
Key object would be:
Microsoft.Win32.RegistryKey key;
Now this key object can be set to create a Subkey in the parent
folder. In the example below, we have used the CurrentUser as
the parent folder:
key =
Microsoft.Win32.Registry.ClassesRoot.CreateSubKey("CS
harp_Website");
Next we can set the Value of this Field using the SetValue()
funtion. See below:
key.SetValue("Really", "Yes!");
The output shown below:

The Code-Kings Ebook (July 2013)
106 | Page
www.Code-Kings.com


As you will see in the picture below, you can select different
parent folders(such as ClassesRoot, CurrentConfig etc.) to create
and set different key values:





The Code-Kings Ebook (July 2013)
107 | Page
www.Code-Kings.com
Read Registry Values

Previously, we saw how to create a registry i.e. write a value
into the Windows registry. Now we shall retrieve back the exact
value that we had written before. To do this we need to retrieve
the value in a String variable.

We shall take the value by its exact location & the name of the
property. Note that the property resides in a folder and the value
we read is the Data of that property. Have a look at the present
snapshot of the system:


Root Folder is HKEY_CURRENT_USER
Parent Folder is CSharp_Website
Property/Attribute/Key Name is Really
Property/Attribute/Key Value is Yes!

The GetValue() function does this work impressively for us.
Considering the values we have above, we create a String that
The Code-Kings Ebook (July 2013)
108 | Page
www.Code-Kings.com
provides the correct path for the Key Value. The code is shown
below:


private void btnReadReg_Click(object sender, EventArgs e)
{
string x =
(string)Registry.GetValue("HKEY_CURRENT_USER\\CSharp
_Website","Really","DefaultValue");
MessageBox.Show(x,"Read Registry");

}













The Code-Kings Ebook (July 2013)
109 | Page
www.Code-Kings.com
Upcasting and Downcating

Upcasting is basically an object creation mechanism by which
we create objects by referring to their base class. We do this by
replacing the sub-class name by the base-class name in the
object definition. This particularly comes in handy when you
know that a specialized object created will not necessarily use
all the functions of a specialized sub-class has got to offer. So,
replace a sub-class(inherited class) by a base-class and all you
have done is Upcasting.



This concept can be well understood if we take an example. Lets
suppose we have three classes. One parent or generalized class
called the LIVING_THINGS and the two
subclasses ANIMAL and BIRD which inherit from the former.
The parent class or the baseclass has the function,
The Code-Kings Ebook (July 2013)
110 | Page
www.Code-Kings.com
say Born()and Die(). The specialized class have the
functions,
say Run() and Fly() for ANIMAL and BIRD respectively.

To create an ANIMAL and BIRD object you would usually use
the syntax below:
ANIMAL animal = new ANIMAL();
BIRD bird = new BIRD();
In the code above, the methods Run()and Fly() work
perfectly with the objects created. This is the normal way you
would use to create the objects. The reference used to create the
object is exactly the same as the object type created during run-
time. The methods of the subclass work just fine.

But, to create an Upcast, you would use the syntax below:
LIVING_THINGS animal = new ANIMAL();
In the code above, even though we have created an object of the
type ANIMAL and BIRD, the reference used is actually of the
base-class. Therefore the methods Run() and Fly() are not
available to these objects. Instead only the functions available in
the base-class such as Born() and Die() are available.

This can be useful if you want only basic functions available at
the start and want to later convert these objects of their original
types to make their specialized functions available.

This can be done with the help of Downcasting. Downcasting
can change the reference types of these objects to the specialized
The Code-Kings Ebook (July 2013)
111 | Page
www.Code-Kings.com
subclass to make available the functions which were not
available otherwise. Watch the code below:
ANIMAL new_animal = animal as ANIMAL;
In the above code, we created a new object and converted it to
an ANIMAL type. It should be a good practice to actually check
if the object to be converted supports the conversion. This can
be done with the help of the is keyword

if (animal is ANIMAL)
{
ANIMAL new_animal = animal as ANIMAL;
new_animal.Run( );
}

With the help of Downcasting, we restored all the functions and
properties that the ANIMAL object should have. Now it behaves
as a proper ANIMAL object.











The Code-Kings Ebook (July 2013)
112 | Page
www.Code-Kings.com
Enumerations
Enumerations or simply Enums in short provide convenient
ways to create and access named numeric constants. These
constants can have custom Indexable values that represent each
individual element. Unlike arrays, they can have values which
are not incremental in steps of 1. Also, these values can be of
types other than integers (which is the default) such as bytes,
Boolean etc.
A single Enumeration itself has a group of values associated
with it. We create an Enum Object before attempting to use the
functions that are offered. This value when used with a dot
operator on an Enumeration gives the state of the Enumeration
Object. When we initialize new Enums of a previously defined
Enum, we dont use the new operator. The new Enums are
almost immediately created and initialized to an initial value
within the Enum.
Create an Enum
Lets take an example to illustrate this. The traffic lights should
provide a simple but complete example on how to create and use
an Enumeration. Start off by creating the Enumeration itself:

enum TrafficLights

{
Red,
Yellow,
Green
};

The Code-Kings Ebook (July 2013)
113 | Page
www.Code-Kings.com
Note how commas are used instead of semicolons used
otherwise. Next, create a traffic lights object to make use of the
Enum. The Enum is initialized to the value Red:


TrafficLights Light1 = TrafficLights.Red;


To change the value of this Enum from Red to say, Green:


Light1 = TrafficLights.Green;


Converting Enums between their Name and Value

Now we shall see what value is possessed by an Enum. This
value is actually the integer value of the present selected string
value. Casting explicitly can bring out the value of the selection.
To perform a conversion, we must know the corresponding
values of our traffic lights first. Since we have not explicitly
defined values, the implicit values are 0 for Red, 1 for Yellow
and 2 for Green. Lets suppose we have an Integer that takes in
the present underlying Integer value of the Traffic Signal:

int I;

I = (int)Light1;

The method used above is called Explicit Casting. Simply put
the variable type in brackets before the Enum to convert it to its
integral value.

The Code-Kings Ebook (July 2013)
114 | Page
www.Code-Kings.com
We can also do the reverse i.e. we can get the Enum members
from their Integer values. Just use the Explicit Cast again. See
below how to create a Red traffic signal from its Integer value 0:


TrafficLights LightR = (TrafficLights)0;


Now that we know Enums have Integer values associated with
them, then it is only logical to think that they can be used to
perform logical operations as well. Suppose we have a traffic
light and want to check if its not Red i.e. Green or Yellow. Then
we can use the following code to apply the check through an if
statement:

if (LightR > 0)

{

//Do This

}










The Code-Kings Ebook (July 2013)
115 | Page
www.Code-Kings.com
Read an External Text File

This C# program shows you how you can load an external Text
File from your Hard Disk into a Multi-Line TextBox. The
procedure consists of creating the StreamWriter object to begin
working which is the feature of this code. Watch the image
above.


The coding begins with the choose path button. We use it to
open up a OpenFileDialogBox which is used to retrieve the file
path of an existing file on a hard disk. Opening it consists of
invoking the Show() method. When the user successfully selects
a valid file, the FileName property of the OpenFileDialogBox is
updated to carry the full length String value of the file location.
The Code-Kings Ebook (July 2013)
116 | Page
www.Code-Kings.com
Then we save the file location in the textbox named txtChoose
Watch the code:

private void btnChoose_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
txtChoose.Text = openFileDialog1.FileName.ToString();
}


Now that we have the file location of the text file, we can load
the text file Line by Line into the Multi-Line extbox. Note that
when we create a textbox by default it is a single lined textbox.
To make it Multi-Line simply change the Multiline property of
the textbox to true. Watch the code below to create a
StreamReader Object and fill the Multi-Line textbox
subsequently:


private void btnLoadFile_Click(object sender, EventArgs e)
{
int counter = 0;
string CurrentLine;

// Read the file and display it line by line.
System.IO.StreamReader FileToRead =
new System.IO.StreamReader(txtChoose.Text);

while ((CurrentLine = FileToRead.ReadLine()) != null)
{
MainTextBox.AppendText(CurrentLine);
MainTextBox.AppendText("\n");
counter++;
}

FileToRead.Close();

Console.ReadLine();
The Code-Kings Ebook (July 2013)
117 | Page
www.Code-Kings.com
}


In the above code, we have a while loop to keep reading lines
until we have reached to the end of the file. We append lines
using the AppendText() function inside the for loop. This
function does not write lines by default. This is because the text
is read as a sequence of characters only. Thus to create the line
by line effect, we add the AppendText("\n") method. Without
this the text loaded would look inconsistent.

Do not forget to close the open file through
the FileToRead.Close() method. In case a file is open this
program or any other program, you would not be able to edit it
externally.














The Code-Kings Ebook (July 2013)
118 | Page
www.Code-Kings.com
Create New Threads

This WinForms C# Application will show you the basics of
creating and using a thread and a bit more. It will actually show
you multiple threads working simultaneously. As you know that
threads are meant to do multiple jobs at a time by utilizing the
different logical cores of the CPU, we will use this to work the
value of multiple Int64 variables. See the application screenshot
when the application starts and look for the source code at the
end:





The Code-Kings Ebook (July 2013)
119 | Page
www.Code-Kings.com

What we want in our above application is to created two Int64
variables and simply increase their values using two different
threads. When we click the START button, the thread initializes
and the counting process starts. The value of the variable
increases continuously in the background. When we click the
Show Current Value button, the value currently stored in the
Int64 variable is shown in the TextBox. You may click the Show
Current Value button as many times as you want. Everytime you
get an incremented value that we have managed to get via
an Infinite Loop.

Lets start by adding the code to create the variables in the program:


public Int64 FirstInt = new Int64();

public Int64 SecondInt = new Int64();

As you might have guessed the FirstInt and SecondInt are the
variables that we will work with. These are defined at the start
of the code outside the scope of all functions so that they are
visible to every function.

Next we create the two functions that will work on the two
different threads. These functions will start to increase the value
of the two variables continuously using an infinite loop. To
create an Infinite Loop, simple leave the middle section of the
loop blank. i.e. There will be no check applied during the
iteration process so that the loop never checks for a value to stop
itself. Watch the code below:


private void StartTextCount1()
The Code-Kings Ebook (July 2013)
120 | Page
www.Code-Kings.com
{
for (int m = 0; ; m++)
{
FirstInt++;
}
}

private void StartTextCount2()
{
for (int n = 0; ; n++)
{
SecondInt++;
}
}


The next thing we need to assure is that we have initialized the
value of our variables. Because incrementing the values of an
uninitialized variable may result in an error or may give garbage
values. So in the Load() event of the form we set the value of the
variables to 0 each. See code below:

private void Form1_Load(object sender, EventArgs e)
{
FirstInt = 0;
SecondInt = 0;
}

Now that all values have been set up and the form loaded, we
need the simple code to create a new thread when the first start
button that is above of two is clicked. See code below to create a
new thread:

private void Start1_Click(object sender, EventArgs e)
{
System.Threading.Thread Thread1 =
new System.Threading.Thread(StartTextCount1);
The Code-Kings Ebook (July 2013)
121 | Page
www.Code-Kings.com

Thread1.Start();
}

The thread created is called Thread1. This thread runs
the StartTextCount() function. The thread requires the parameter
that is the function that it will work on. When we call the Start()
method of the Thread, the method in the parameter is called via
the thread. Similarly write code for the second button to create
the second thread:

private void Start2_Click(object sender, EventArgs e)
{
System.Threading.Thread Thread2 =
new System.Threading.Thread(StartTextCount2);

Thread2.Start();
}

The last thing that remains is to create the code to show the
variable value into the TextBox. This code below converts the
Int64 value of the variable into a String. Then it displays it in the
Black background TextBox called Text1. The same code applies
for the second TextBox named Text2.

private void ShowValue1_Click(object sender, EventArgs e)
{
Text1.Text = FirstInt.ToString();
}


private void ShowValue2_Click(object sender, EventArgs e)
{
Text2.Text = SecondInt.ToString();
}


The output screenshots below were taken at different intervals:
The Code-Kings Ebook (July 2013)
122 | Page
www.Code-Kings.com











The Code-Kings Ebook (July 2013)
123 | Page
www.Code-Kings.com
Create Web Browser

This article shows you how to easily create a Web Browser with
minimal standard functions containing all standard buttons like
the Back, Forward Stop and Home buttons. See below image for
more details:




Watch code below with step by step explanations:

namespace Web_Browser_CSharp
The Code-Kings Ebook (July 2013)
124 | Page
www.Code-Kings.com
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

The browser understands Uri as the actual web address of a
website. The Load event of the form sets the URL of
WebBrowser to the String that is present in the address bar
TextBox to create a URI. See below on how to create a Uri
object:

private void Form1_Load(object sender, EventArgs e)
{
Uri url = new Uri(txtAddress.Text);
webBrowser1.Url = url;
}

The first event that occurs when a new page loads is the
Navigating Event. This occurs just before the Web
Browser starts loading the next page.



private void webBrowser1_Navigating(
object sender, WebBrowserNavigatingEventHandler e)
{
lblStatus.Text = "Page Navigating";
}

The second event fired is the Navigated() Event that
acknowledges about the success of Navigating and loading the
The Code-Kings Ebook (July 2013)
125 | Page
www.Code-Kings.com
page. After the Navigated() Event, the Browser continues to
load the files of the Web Page.




private void webBrowser1_Navigated(
object sender, WebBrowserNavigatedEventHandler e)
{
lblStatus.Text = "Page Navigated";
}

After all the Files in the Web Page have been loaded,
the Browser fires the DocumentCompleted() Event. One very
important point to notice here: when a document completes
loading, its page URL usually differs by some added text. This
happens after loading of the page is done. This text in the
addressbar is NOT the exact same text that we wrote in the
Address bar. Take for example you went to www.ABC.com but
after you reached there, you were redirected to
www.ABC.com/home/guest. Therefore, we need to continously
update the address bar.




private void webBrowser1_DocumentCompleted(
object sender, WebBrowserDocumentCompletedEventArgs e)
{
lblStatus.Text = "Page Loaded Successfully";
txtAddress.Text = webBrowser1.Url.ToString();
}

The Code-Kings Ebook (July 2013)
126 | Page
www.Code-Kings.com
When the Go button is clicked we check for a valid URL
supplied and supply it to the Web Browser for Navigation.

private void btnGo_Click(object sender, EventArgs e)
{
try
{
Uri url = new Uri(txtAddress.Text);
webBrowser1.Url = url;
}
catch (Exception)
{
MessageBox.Show("Invalid URL Supplied", "Error");
}
}

When the Stop Sign is clicked, the Browser cancels all
pending Navigations and stops all stops any Dynamic Page
Elements such as sound and animations.

private void btnStop_Click(object sender, EventArgs e)
{
webBrowser1.Stop();
}

The GoBack() method of the Web Browser does what it
reads i.e. it loads the previous page in the Web Browser.

private void btnBack_Click(object sender, EventArgs e)
{
webBrowser1.GoBack();
}

Similarly the GoForward() method goes one page forward if
available.

private void btnForward_Click(object sender, EventArgs e)
{
The Code-Kings Ebook (July 2013)
127 | Page
www.Code-Kings.com
webBrowser1.GoForward();
}

When the Home button is clicked, the Web Browser navigates to
Home Page of its Current User.

private void btnGoHome_Click(object sender, EventArgs e)
{
webBrowser1.GoHome();
}


The following code handles the Search feture of your Web
Browser. A set of predefined text followed by your search
keyword are to be supplied to the Web Browser for Navigation
and that's it. I have used the if....else statements to check for the
search engine and then set the URL parameter of the Web
Browser.

private void btnSearch_Click(object sender, EventArgs e)
{
if (radioGoogle.Checked == true)
{
Uri url = new
Uri("http://google.com/search?q=" + textSearch.Text);
webBrowser1.Url = url;
}

if (radioBing.Checked == true)
{
Uri url = new
Uri("http://www.bing.com/search?q=" + textSearch.Text);
webBrowser1.Url = url;
}

if (radioAsk.Checked == true)
{
Uri url = new
Uri("http://www.ask.com/web?q=" + textSearch.Text);
The Code-Kings Ebook (July 2013)
128 | Page
www.Code-Kings.com
webBrowser1.Url = url;
}
}

private void btnSavePage_Click(object sender, EventArgs e)
{
webBrowser1.ShowSaveAsDialog();
}

private void btnPrint_Click(object sender, EventArgs e)
{
webBrowser1.ShowPrintDialog();
}

private void btnPrintPreview_Click(object sender, EventArgs e)
{
webBrowser1.ShowPrintPreviewDialog();
}

private void btnPageSettings_Click(object sender, EventArgs e)
{
webBrowser1.ShowPageSetupDialog();
}

The code below deals with the showing of another form that
shows the source code the current Web Page. We have set the
public string value to the source html and then it shows in the
next form. When the next form loads, it copies the public string
value into its RichTextBox.

The Code-Kings Ebook (July 2013)
129 | Page
www.Code-Kings.com


private void btnSourceCode_Click(object sender, EventArgs e)
{
frmSourceCode frm = new frmSourceCode();
frm.strhtml = webBrowser1.DocumentText;
frm.Show();
}

}
}




The Code-Kings Ebook (July 2013)
130 | Page
www.Code-Kings.com
Draw Bitmap on Screen

Would you like to draw a bitmap on the screen? Drawing on the
WinForms is very easy using the Graphics() Class and Objects.
You can draw any type of image by taking the image from your
HDD and including file types like BMP, JPEG, PNG etc. Watch
the screenshot of a file that is drawn to the WinForm:




The image with the Red background is drawn on a Panel. The
panel acts as the Graphics() surface to which we have drawn the
image. We can choose to draw on any control including the
Form itself. In the case above, we have used the whole Panel to
draw an unscaled image simply taken from the HDD. Press the
The Code-Kings Ebook (July 2013)
131 | Page
www.Code-Kings.com
Choose Bitmap button on the Top Right and you will be
presented with the OpenFileDialog. You can then choose your
image file and set it to display on the Form's Panel. See code
below followed by the source code at the end:

namespace Drawing_a_Bitmap
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

Below we have created the Graphics() object with which we
shall work in the program. This Graphics() object is used to
create surfaces and to draw to them. We have used the Panel
control to draw the Bitmap on. The first thing we need to do is
give the choice to the user to choose the bitmap file through a
OpenFileDialog. Then we capture the image in a Bitmap Object
by supplying the FileName of the OpenFileDialog as a
parameter. Then we simply create the drawing surface using
the CreateGraphics() function. The final line of code draws the
bitmap on the position 0,0 starting from the Top Left corner as
the starting point.

Graphics graphics;

private void btnChoose_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() ==
System.Windows.Forms.DialogResult.OK)
{
Bitmap bitmap = new Bitmap(openFileDialog1.FileName.ToString());
bitmap.InitializeLifetimeService();

The Code-Kings Ebook (July 2013)
132 | Page
www.Code-Kings.com
graphics = this.TestPanel.CreateGraphics();
graphics.DrawImage(bitmap, 0, 0);
}
}

The code below simply has one difference and that is we have
supplied a fourth and fifth parameter to the DrawImage()
function. This overload gives us the Custom Width in the 4th
Parameter and the Custom Height in the 5th Parameter. These
values are taken and converted to an Integer Type beforehand
into the variables x and y respectively from the two TextBoxes
labeled Width and Height on the Form.

private void btnResizedBitmap_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() ==
System.Windows.Forms.DialogResult.OK)
{
Bitmap bitmap = new Bitmap(openFileDialog1.FileName.ToString());
bitmap.InitializeLifetimeService();

int x = Convert.ToInt16(txtWidth.Text);
int y = Convert.ToInt16(txtHeight.Text);

graphics = this.TestPanel.CreateGraphics();
graphics.DrawImage(bitmap, 0, 0, x, y);
}
}

The Code-Kings Ebook (July 2013)
133 | Page
www.Code-Kings.com



On pressing the Reset button, we Clear() the Graphics Object
which brings a plane solid color to the drawing surface of our
choice.

private void btnResetBitmap_Click(object sender, EventArgs e)
{
graphics.Clear(Color.White);
}

private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
}
}

The Code-Kings Ebook (July 2013)
134 | Page
www.Code-Kings.com
The graphics drawn above is not persistent i.e. when we resize
or mimize the form, we may encounter a loss of a portion or the
whole image. To avoid this, we must use the OnPaint() function
to draw all drawings.






















The Code-Kings Ebook (July 2013)
135 | Page
www.Code-Kings.com
Identify Pressed Key






The Code-Kings Ebook (July 2013)
136 | Page
www.Code-Kings.com
Now you can capture any key pressed on the keyboard, not only
restricted to the English or your language letters but also various
other keys such as the Windows Key, Properties Key, F1, F2
and other function buttons, the Home, PageUp and PageDown
etc.

When you check the value of e.KeyCode.ToString() for various
other keys such as the WinKey you will get a value of "LWin"
for the String returned. The value of the KeyCode() is exactly
the same for the capital and small letters of the languages but the
value for the special buttons varies as shown below:

"LWin" for WinKey (Windows Key)
"ControlKey" for Control Key
"ShiftKey" for Shift Key
"Menu" for the Alt Key (Alternate)
"Apps" for the Property Key (usually beside the Right Ctrl
Key)
"Oemtilde" for the tilde Key (Left of the Numerical 1)
"Escape" for Escape Key
"Next" for Page Down
"Up" for Up, "Down" for Down etc.
"Return" for Enter Key
"A" for A; "B" for B "C" for C etc.
"a" for a; "b" for b; "c" for c etc.

Watch Code Below followed by the Source Code:

namespace Check_Key_Pressed
{
public partial class Form1 : Form
The Code-Kings Ebook (July 2013)
137 | Page
www.Code-Kings.com
{
public Form1()
{
InitializeComponent();

this.KeyDown += Form1_KeyDown;
}

void Form1_KeyDown(object sender, KeyEventArgs e)
{
lblKeyPressed.Text = e.KeyCode.ToString();
if (e.KeyCode.ToString() == "ControlKey")
{
checkCtrl.Checked = !checkCtrl.Checked;
}
if (e.KeyCode.ToString() == "ShiftKey")
{
checkShift.Checked = !checkShift.Checked;
}
if (e.KeyCode.ToString() == "Menu")
{
checkAlt.Checked = !checkAlt.Checked;
}
}

private void Form1_Load(object sender, EventArgs e)
{
MessageBox.Show("Created by www.Code-Kings.com");
}
}
}





The Code-Kings Ebook (July 2013)
138 | Page
www.Code-Kings.com
Display Files & Folders
You can easily list and display all the files and folders in a C#
application using the DirectoryInfo class. First have a look at the
application screenshot which uses this class to display the Files
and Folders in a specified directory. All the Files and Folders are
displayed in a ListView.



An object created with the DirectoryInfo class has two methods
viz. GetFiles() and GetDirectories() which return an array of
Files and Directories respectively. The GetFiles() method can
only be used in the subclass FileInfo. These Files and
Directories are then displayed in a ListView by converting the
Files and Directories to a ListViewItem. These ListViewItems
are created by converting and using the Name Property of
the FileInfo and DirectoryInfo subclasses.


Every File and Directory is contained in a FileInfo and
DirectoryInfo class encapsulated with all the properties and
functions that help us to identify and use the Files and
The Code-Kings Ebook (July 2013)
139 | Page
www.Code-Kings.com
Directories. The properties include Name, FullName, Creation
Time, LastAccessTime, LastWriteTime, Parent, Root to name a
few. The functions that apply to this class are the Create,
Refresh, Delete, MoveTo etc. These are just some of the
functions and properties available to the FileInfo and
DirectoryInfo Class. There are many more to explore so make
sure you try them all. These are properties that can help identify
a particular file or a group of files when you have a large
collection. You can filter files from a directory by setting values
for these above mentioned properties. We will just use
the Name Property to list the Name of the Files and Folders in a
Directory for a quick understanding. You can use any other
property in much the same way. Watch the code below:

namespace Show_Files_and_Folders
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
MessageBox.Show("http://www.code-kings.com");
}

private void btnChooseDir_Click(object sender, EventArgs e)
{
if (DirDialog1.ShowDialog() ==
System.Windows.Forms.DialogResult.OK)
{
txtDirLocation.Text =
DirDialog1.SelectedPath.ToString();
}
}

private void btnShowFiles_Click(object sender, EventArgs e)
The Code-Kings Ebook (July 2013)
140 | Page
www.Code-Kings.com
{
System.IO.DirectoryInfo dir
= new System.IO.DirectoryInfo(txtDirLocation.Text);
foreach (System.IO.FileInfo f in dir.GetFiles("*.*"))
{
ListViewItem lSingleItem =
listView1.Items.Add(f.Name);
}
}

private void btnShowFolders_Click(object sender, EventArgs e)
{
System.IO.DirectoryInfo dir
= new System.IO.DirectoryInfo(txtDirLocation.Text);
foreach (System.IO.DirectoryInfo getdirs in dir.GetDirecto
ries("*.*"))
{
ListViewItem lSingleItem =
listView2.Items.Add(getdirs..Name);
}
}
}
}









The Code-Kings Ebook (July 2013)
141 | Page
www.Code-Kings.com
Printing a Windows Form
The objective here is to print a Windows Form to the Printer or a
File on the HDD. You can also have a Print Preview before you
print a WinForm. See the Form below that we shall print. We
will encounter one small problem i.e. the button, radio buttton
and textbox are not required for printing. We only wish to print
the written text written above in Green color. There is VS 2012
source code at the very end. See the code and explanations
below the image:



Visual Studio 2012 and 2010 as well come with a very special
and useful tool in the tool box. Located in the Visual Basic
PowerPacks section with many other useful tools(that we shall
explore in later posts), it is named PrintForm and makes
The Code-Kings Ebook (July 2013)
142 | Page
www.Code-Kings.com
printing very easy for everyone. The whole form prints as it is to
a file or printer. Also note that the borders of the window are
NOT printed which is really cool! So you dont have to worry
about the borders but you do have to worry about some
unwanted stuff, like for example the "Ready To Print()" button
with the other radio buttons and textbox shown above iare not
really needed in the print. So we simply trim the size of the form
before we fire the Print() function of the PrintForm. Watch the
code below:


namespace Print_a_WinForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

// The PrintAction determines what the PrintForm object actually
// does. It has three simple options to choose.
// Below, we chose it to "PrintToPreview"
// It simply opens a Print Preview Window.

private void btnPrintPreview_CheckedChanged(object sender, EventArgs e)
{
if (btnPrintPreview.Checked == true)
{
printForm1.PrintAction =
System.Drawing.Printing.PrintAction.PrintToPreview;
}
}

// Below we have set the PrintAction to PrintToFile
// It does exactly as it says.
// It creates a Image file on the Hard Disk of the
// current state/look of the Windows form.
The Code-Kings Ebook (July 2013)
143 | Page
www.Code-Kings.com
// The file name is selected in the TextBox and set to the
// PrintFileName property of the PrintForm object.

private void btnPrintToFile_CheckedChanged(object sender, EventArgs e)
{
if (btnPrintToFile.Checked == true)
{
printForm1.PrintAction =
System.Drawing.Printing.PrintAction.PrintToFile;
printForm1.PrintFileName = txtFileName.Text;
}
}

// Set the PrintAction to PrintToPrinter
// to give output to a physical printer that you may have.

private void btnPrintToPrinter_CheckedChanged(object sender, EventArgs e)
{
if (btnPrintToPrinter.Checked == true)
{
printForm1.PrintAction =
System.Drawing.Printing.PrintAction.PrintToPrinter;
}
}
The Code-Kings Ebook (July 2013)
144 | Page
www.Code-Kings.com


// The process of trimming the unwanted controls is
// by simply reducing the height of the Form.
//Here we have reduced it from 376 to 289.
// After that the unwanted controls are no longer visible
// and it is safe to print the form.

private void btnReady_Click(object sender, EventArgs e)
{
this.Height = 289;
printForm1.Print();
}
}
}
The Code-Kings Ebook (July 2013)
145 | Page
www.Code-Kings.com












The Code-Kings Ebook (July 2013)
146 | Page
www.Code-Kings.com
Optional Parameters
Optional Arguments were introduced in C# 4.0 and this article
will show you how to use them. Optional Arguments are
necessary when you specify functions that have a large number
of arguments. It can cut down time by making you pass on
argument values to the most needy parameters in a situation.

Optional Arguments are what their name suggests i.e. even if
you do not specify them, its perfectly OK. But it doesn't mean
that they have not taken a value. In fact we specify some default
values that the Optional Parameters take when values are not
supplied in the function call. In this way we gain the
functionality of easily setting values once and using these values
several times as a default unless something different is needed.

The values that we supply in the function Definition are some
constants. Note that we can only supply one default value for
one parameter. This makes sense as there can only be one
default value for one property by definition. But this also means
that multiple values cannot be assigned and given priorities in
different situations. We have to check for ourselves which value
fits in best in a given situation and supply it in a function call to
that variable. These default values are to be used in case no
value is supplied in the function call. These values are specified
by typing in equations(with a single = sign) instead of just the
declaration of variables.

For example, we write

static void Func(Str = "Default Value")

The Code-Kings Ebook (July 2013)
147 | Page
www.Code-Kings.com
instead of static void Func(int Str)

If you didn't know this technique, you were probably using
Function Overloading, but that technique requires multiple
declaration of the same function. Using this technique you can
define the function only once and have the functionality of
multiple function declarations.

Consider a function that is defined with two optional parameters.
When only one parameter is supplied, the
second parameter takes the default value. We can then write the
function in such a way as to check if the second parameter value
received or not. If the parameter value is the default one then
just ignore it and continue to work with the first parameter
value. Thus we have the function overloading effect in which a
same named function takes on two different tasks.

When we supply two different parameters, the function works
with both the values. This can be easily achieved using the if
statement. Just check which parameter has and does not have
the default value.

When using this technique it is best that you have declared
optional & required parameters both. i.e. you can specify both
types of parameters in your function declaration to get the most
out of this technique.

An example of a function that uses both types of parameters is
shown below:

static void Func(String Name, int Age, String Address =
"N/A")

The Code-Kings Ebook (July 2013)
148 | Page
www.Code-Kings.com
In the example above, Name & Age are required parameters.
The string Address is optional, if not specified, then it would
take the value "N/A" meaning the Address is not available.

For the above example, you could have two types of function
calls:

Func("John Chow", 30, "America");

Func("John Chow", 30);

That's it from Optional Arguments. Have a look at Named
Arguments for more information on parameter types.









The Code-Kings Ebook (July 2013)
149 | Page
www.Code-Kings.com
Named Arguments
Named Arguments are an alternative way for specifying of
parameter values in function calls. They work so that the
position of the parameters would not pose problems. Therefore it
reduces the headache of remembering the positions of all
parameters for a function.

They work in a very simple way. When we call a function, we
would write the name of the parameter before specifying a value
for the parameter. In this way, the position of the argument will
not matter as the compiler would tally the name of the parameter
against the parameter value. This makes it unnecessary to
remember the organisation of the parameters in the function
definition.

Consider a function definition below:


static int remainder(int dividend, int divisor)

{
return( dividend % divisor );
}

Now we call this function using two methods with a Named
Parameter:


int a = remainder(dividend: 10 , divisor:5);

The Code-Kings Ebook (July 2013)
150 | Page
www.Code-Kings.com
int a = remainder(divisor:5 , dividend: 10);

Note that the position of the arguments have been interchanged,
both the above methods will produce the same output i.e. they
would set the value of a as 0(which is the remainder when
dividing 10 by 5).

That's it from Named Arguments. Have a look at Optional
Arguments for more.












The Code-Kings Ebook (July 2013)
151 | Page
www.Code-Kings.com
Show and Invert RGB Colors
This post will demonstrate how to show and convert colors
when the Red Green & Blue values of those colors are given.
We simple use a function and supply the Red, Green and Blue
components in the parameter list. We shall also see how to
Invert a color. In the image below the text color is set by the
user. The background color is automatically set which is the
Invert of the Text color. See image below to have a look at the
final output of our WinForms application:




The Color.FromArgb( ) function sets the color of any element
by taking in 3 basic parameters. These parameters set the RGB
components and create the color we need. The 'A' in Argb
specifies the Alpha value which sets the brightness of the color.
The Code-Kings Ebook (July 2013)
152 | Page
www.Code-Kings.com
Although its not necessary, it is a good practice to set the Alpha
value of a color. This enables you to fine tune the color even
further.




We also see how to Invert a color. Inverting a color simply
means taking the opposite value of each component and merge
them to create the Inverted color. To perform inversion in the
RGB values, we simply minus the color from the integer 255. If
we have a color component with value 255 then the inverted
color component is (255 - 255) i.e. 0 (Zero). Likewise the color
component with value 100 is (255 - 100) i.e. 155. The invert of
Black is White as we all know. As you can see in the above
image, the invert color of blue is yellow.

using System;
using System.Collections.Generic;
The Code-Kings Ebook (July 2013)
153 | Page
www.Code-Kings.com
using System.Drawing;
using System.Windows.Forms;

namespace Color_Show_by_Integer_Value
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void btnShow_Click(object sender, EventArgs e)
{
int RedValue = Convert.ToInt16(TRed.Text);
int GreenValue = Convert.ToInt16(TGreen.Text);
int BlueValue = Convert.ToInt16(TBlue.Text);

LabelColor.BackColor =
Color.FromArgb(RedValue,GreenValue,BlueValue);

LabelExplain.BackColor =
Color.FromArgb(255 - RedValue, 255 - GreenValue, 255 -
BlueValue);

LabelExplain.ForeColor = Color.FromArgb(RedValue,
GreenValue, BlueValue);
}
}
}





The Code-Kings Ebook (July 2013)
154 | Page
www.Code-Kings.com
Solve Quadratic Equations
You can very easily solve a Quadratic Equation with this small
program. Just enter the values in the 3 text boxes and you will
find the resulting roots(solutions) of the Quadratic equation on
the right. Watch the final output and see the source code further
below:



The C# Code below is simple, structured & complete. Note the
code for the text box change event is similar for all the 3 text
boxes.

namespace Solve_Quadratic_Equation
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
The Code-Kings Ebook (July 2013)
155 | Page
www.Code-Kings.com
}

double a, b, c;

Code to be used if the Determinant of Quadratic
Equation is positive; This code returns the
value to be used when the square root of the
determinant is a real number.

public double DeterminantQuad(double b, double a, double c)
{
return ((b * b) - (4 * a * c));
}

Code to be used if Determinant of Quadratic
Equation is negative; The code below returns
the negative value of the regular determinant.
Since the regular determinant is negative, we
get a positive value in the end(negative of
negative is positive). We then add the letter
"i" in the answer to show that the square root
is taken of a negative number. Therefore
pointing out the unreal root in red color.

public string NegativeDeterminant(double b, double a, double c
)
{
return (((4 * a * c) - (b * b)).ToString());
}

Calculate the First Root of the equation:
The Code-Kings Ebook (July 2013)
156 | Page
www.Code-Kings.com



public string FirstRealRootQuad(double a, double b, double c)
{
if (DeterminantQuad(b, a, c) >= 0)
{
return ((((-b) + (Math.Sqrt(DeterminantQuad(b, a,
c)))) / (2 * a)).ToString());
}
else
{ return ((-b / (2 * a)).ToString() + "+ i" +
(Convert.ToDouble(NegativeDeterminant(b, a, c)) / (2 *
a)).ToString()); }
}

Calculate the Second Root of the equation:



public string SecondRealRootQuad(double a, double b, double c
)
{
The Code-Kings Ebook (July 2013)
157 | Page
www.Code-Kings.com
if (DeterminantQuad(b, a, c) >= 0)
{
return ((((-b) - (Math.Sqrt(DeterminantQuad(b, a,
c)))) / (2 * a)).ToString());
}
else
{ return ((-b / (2 * a)).ToString() + "- i" +
(Convert.ToDouble(NegativeDeterminant(b, a, c)) / (2 *
a)).ToString()); }
}

TextBox Text Change Event Code; This code is similar for all
the 3 Text Boxes

private void QuadA_TextChanged(object sender, EventArgs e)
{
try
{
a = Convert.ToDouble(QuadA.Text);
b = Convert.ToDouble(QuadB.Text);
c = Convert.ToDouble(QuadC.Text);

QuadRootA.Text = FirstRealRootQuad(a, b, c);
QuadRootB.Text = SecondRealRootQuad(a, b, c);
}
catch { }

if (QuadRootA.Text.Contains("i"))
{
QuadRootA.ForeColor = Color.Red;
}
if (QuadRootB.Text.Contains("i"))
{
QuadRootB.ForeColor = Color.Red;
}
}
}



The Code-Kings Ebook (July 2013)
158 | Page
www.Code-Kings.com
Measure Difference between 2 Dates
Getting differences between two given dates is as easy as it can
get. The function used here is
the End_Date.Subtract(Start_Date). This gives us a time span
that has the time interval between the two dates. The time span
can return values in the form of days, years, etc.




You can then simply display the values as Text Strings. See
code below for details on how to display the results in
WinForms. After this, you can see the same program in the
Console Environment.
The Code-Kings Ebook (July 2013)
159 | Page
www.Code-Kings.com

namespace Date_Difference_in_CSharp

{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void dddtpStart_ValueChanged(object sender, Eve
ntArgs e)
{
try
{
DateTime startDate =
(DateTime)dddtpStart.Value;
DateTime endDate = (DateTime)dddtpEnd.Value;
TimeSpan ts = endDate.Subtract(startDate);

ddtxtDays.Text = ts.Days.ToString();
ddtxtDifference.Text =
(Convert.ToDouble(ddtxtDays.Text) / 365).ToString();
}
catch
{
}
}

private void dddtpEnd_ValueChanged(object sender, Event
Args e)
{
try
{
DateTime startDate =
(DateTime)dddtpStart.Value;
DateTime endDate = (DateTime)dddtpEnd.Value;
TimeSpan ts = endDate.Subtract(startDate);

ddtxtDays.Text = ts.Days.ToString();
The Code-Kings Ebook (July 2013)
160 | Page
www.Code-Kings.com
ddtxtDifference.Text =
(Convert.ToDouble(ddtxtDays.Text) / 365).ToString();
}
catch
{
}
}
}
}

Below, you can see a program written in the C# Console
environment that does the same work:



using System;
using System.Text;

namespace Print_and_Get_Date_Difference_in_C_Sharp
{
class Program
{
The Code-Kings Ebook (July 2013)
161 | Page
www.Code-Kings.com
static void Main(string[] args)
{
Console.WriteLine("********************************
***********");
Console.WriteLine("********www.code-
kings.blogspot.com********");
Console.WriteLine("********************************
***********\n");
Console.WriteLine("The Date Today Is:");
DateTime DT = new DateTime();
DT = DateTime.Today.Date;
Console.WriteLine(DT.Date.ToString());

Console.WriteLine("Calculate the difference between
two dates:\n");
int year, month, day;

Console.WriteLine("Enter Start Date");
Console.WriteLine("Enter Year");
year
= Convert.ToInt16(Console.ReadLine().ToString());
Console.WriteLine("Enter Month");
month
= Convert.ToInt16(Console.ReadLine().ToString());
Console.WriteLine("Enter Day");
day
= Convert.ToInt16(Console.ReadLine().ToString());
DateTime DT_Start = new DateTime(year,month,day);

Console.WriteLine("\nEnter End Date");
Console.WriteLine("Enter Year");
year
= Convert.ToInt16(Console.ReadLine().ToString());
Console.WriteLine("Enter Month");
month
= Convert.ToInt16(Console.ReadLine().ToString());
Console.WriteLine("Enter Day");
day
= Convert.ToInt16(Console.ReadLine().ToString());
DateTime DT_End = new DateTime(year, month, day);

The Code-Kings Ebook (July 2013)
162 | Page
www.Code-Kings.com
TimeSpan timespan = DT_End.Subtract(DT_Start);
Console.WriteLine("\nThe Difference is:\n");
Console.WriteLine(timespan.TotalDays.ToString() + "
Days\n");
Console.WriteLine((timespan.TotalDays /
365).ToString() + " Years");

Console.ReadKey();
}
}
}













The Code-Kings Ebook (July 2013)
163 | Page
www.Code-Kings.com






Thank You For Reading

Das könnte Ihnen auch gefallen