32 .net c# csharp programs version 4.0

80
http://www.code-kings.blogspot.com/ Page 1 CSharp [C#] Programs Compilation Ver 4.0 Featured Articles: Hello World Advanced calculator Create controls at runtime Check for Anagrams Indexer Basics Write to Windows Registry Decimal to Binary Caller Information Basics Reverse individual words Named Arguments/Parameters Optional Arguments/Parameters Transpose a Matrix Fibonacci series program Get Date Difference Obtain Local Host IP Change monitor state Linear & Binary search Strings selection property Matrix Multiplication DGV Filter & Expressions Stream Writer Basics Send an Email Databinding Tutorial Create a Right Click Menu Custom user Settings Polymorphism Basics Inheritance Basics Random generator class Auto-complete Feature Database Insert & Retrieve Fetch data from table Drawing with mouse

Upload: hassane2005

Post on 31-Dec-2015

48 views

Category:

Documents


12 download

TRANSCRIPT

Page 1: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 1

CSharp [C] Programs Compilation Ver 40

Featured Articles

Hello World Advanced calculator

Create controls at runtime Check for Anagrams

Indexer Basics Write to Windows Registry

Decimal to Binary Caller Information Basics

Reverse individual words Named ArgumentsParameters

Optional ArgumentsParameters Transpose a Matrix

Fibonacci series program Get Date Difference

Obtain Local Host IP Change monitor state

Linear amp Binary search Strings selection property

Matrix Multiplication DGV Filter amp Expressions

Stream Writer Basics Send an Email

Databinding Tutorial Create a Right Click Menu

Custom user Settings Polymorphism Basics

Inheritance Basics Random generator class

Auto-complete Feature Database Insert amp Retrieve

Fetch data from table Drawing with mouse

httpwwwcode-kingsblogspotcom Page 2

Hello World Program For 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 enabledthe 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 public FrmHelloWorld() InitializeComponent() private void timer1_Tick(object sender EventArgs e) lblWorldvisible = false lblHelloVisible = true timer1Enabled = false timer2Enabled = true

httpwwwcode-kingsblogspotcom Page 3

private void timer2_Tick(object sender EventArgs e) lblHelloVisible = false lblWorldVisible = true timer2Enabled = false timer1Enabled = true

private void cmdClickHere_Click(object sender EventArgs e) if (cmdClickHereText = Click Here ) timer1Enabled = true cmdClickHereText = STOP else if (cmdClickHereText = STOP ) timer1Enabled = false timer2Enabled = false cmdClickHereText = Click Here

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 4

An Advanced Calculator in C

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 +-

sincostan Of course there is no limit to the ways in which we can combine these and create

even more complex formulas The calculator stores different calculations in different textboxes

also showing the operands 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 must 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 ConvertToInt32() which converts its

httpwwwcode-kingsblogspotcom Page 5

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) txtAdditionText = txtXText + + + txtYText + = +

ConvertToString(ConvertToInt32((ConvertToInt32(txtXText))+(ConvertToInt3

2(txtYText))))

private void Subtraction_Click(object sender EventArgs e) txtSubtractionText = txtXText + - + txtYText + = +

ConvertToString(ConvertToInt32((ConvertToInt32(txtXText)) -

(ConvertToInt32(txtYText))))

private void Multiplication_Click(object sender EventArgs e) txtMultiplicationText = txtXText + + txtYText + = +

ConvertToString(ConvertToInt32((ConvertToInt32(txtXText))

(ConvertToInt32(txtYText))))

private void Division_Click(object sender EventArgs e) txtDivisionText = txtXText + + txtYText + = +

ConvertToString(ConvertToInt32((ConvertToInt32(txtXText))

(ConvertToInt32(txtYText))))

private void SinX_Click(object sender EventArgs e) txtSinXText = Sin +txtXText + = +

ConvertToString(MathSin(ConvertToDouble(txtXText))) private void CosX_Click(object sender EventArgs e) txtCosXText = Cos + txtXText + = +

ConvertToString(MathCos(ConvertToDouble(txtXText)))

httpwwwcode-kingsblogspotcom Page 6

private void TanX_Click(object sender EventArgs e) txtTanXText = Tan + txtXText + = +

ConvertToString(MathTan(ConvertToDouble(txtXText)))

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 7

Create Controls at Runtime in C 5

Sometimes you might want to create a user control at runtime There are times when you are not

sure of what controls to include during the designing phase of your forms In these cases what

usally is done is that we draw all available controls in the designer and at runtime we simply

make the controls invisible during runtime leaving us with workable visible controls But this is

not the right method What should be done is exactly illustrated below You should draw the

controls at runtime Yes you should draw the controls only 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 method to create them If you look carefully in the

Designer of any form you will find codes that initiate the creation of controls You will see some

properties set leaving other properties default And this is exactly what we are doing here We

are writing code behinf the Fom that creates the controls with some properties set by ourselves amp

others are simply set to their default value by the Compiler

The main steps to draw controls are summarized below

CreateDefine the control or Array of controls

Set the properties of the control or individual controls in case of Arrays

Add the controls to the form or other parent containers such as Panels

Call the Show() method to display the control

Thats it

httpwwwcode-kingsblogspotcom Page 8

The code below shows how to draw controls

namespace CreateControlsAtRuntime 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 lt= 6 i++) tb[i] = new TextBox() tb[i]Width = 150 tb[i]Left = 20 tb[i]Top = (30 i) + 30 tb[i]Text = Text Box Number + iToString() thisControlsAdd(tb[i]) tb[i]Show()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 9

Check for Anagrams in Net C

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 for 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 lt aLength c++) first[a[c] - a]++ c = 0 for (c=0 cltbLength c++) second[b[c] - a]++ for (c = 0 c lt 26 c++) if (first[c] = second[c]) return 0 return 1

httpwwwcode-kingsblogspotcom Page 10

using System namespace Anagram_Test class Program static void Main(string[] args) ClassCheckAnagram cca = new ClassCheckAnagram() ConsoleWriteLine(Enter first stringn) string aa = ConsoleReadLine() char[] a = aaToCharArray() ConsoleWriteLine(nEnter second stringn) string bb = ConsoleReadLine() char[] b = bbToCharArray() int flag = ccacheck_anagram(a b) if (flag == 1) ConsoleWriteLine(nThey are anagramsn) else ConsoleWriteLine(nThey are not anagramsn) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 11

Using Indexers in C 5

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

obj1RollNumberVariable[0] obj1RollNumberVariable[1]

where RollNumberVariable would be the Integer variable

Now that you have learnt how to index your class amp 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 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 lt size i++) RollNumberVariable[i] = 0

httpwwwcode-kingsblogspotcom Page 12

public Int16 this[int pos] get return RollNumberVariable[pos] set RollNumberVariable[pos] = value using System namespace Indexers_Example class Program static void Main(string[] args) Int16 size = 5 Indexers obj1 = new Indexers(size) for (int i = 0 i lt size i++) obj1[i] = (short)i ConsoleWriteLine(nIndexer Outputn) for (int i = 0 i lt size i++) ConsoleWriteLine(Next Roll No + obj1[i]) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 13

How to Write into Windows Registry in C

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 as shown below

The Keys at the parent level are HKEY_CLASSES_ROOT HKEY_CURRENT_USER etc When we refer to

these keys in our C program code we omit the HKEY amp the underscores So to refer to the

HKEY_CURRENT_USER we use simply CurrentUser as the reference Well this reference is available

from the MicrosoftWin32Registry class This Registry class is available through the reference

using MicrosoftWin32

We use this reference to create a Key object An example of a Key object would be

MicrosoftWin32RegistryKey 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 = MicrosoftWin32RegistryClassesRootCreateSubKey(CSharp_Website)

Next we can set the Value of this Field using the SetValue() funtion See below

keySetValue(Really Yes)

httpwwwcode-kingsblogspotcom Page 14

The output shown below

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 15

Convert From Decimal to Binary System

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 gtgt

using System

namespace convert_decimal_to_binary

class Program

static void Main(string[] args)

int n c k

ConsoleWriteLine(Enter an integer in Decimal number systemn)

n = ConvertToInt32(ConsoleReadLine())

ConsoleWriteLine(nBinary Equivalent isn)

for (c = 31 c gt= 0 c--)

k = n gtgt c

if (ConvertToBoolean(k amp 1))

ConsoleWrite(1)

else

ConsoleWrite(0)

ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 16

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 TraceWriteLine() 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)

TraceWriteLine(message + message)

TraceWriteLine(member name + memberName)

TraceWriteLine(source file path + sourceFilePath)

TraceWriteLine(source line number + sourceLineNumber)

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

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 17

Reverse the Words in a Given 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 = strSourceSplit(new char[] ) string strReverse = stringEmpty for (int i = arySourceLength - 1 i gt= 0 i--) strReverse = strReverse + + arySource[i] ConsoleWriteLine(Original String nn + strSource) ConsoleWriteLine(nnReversed String nn + strReverse) return strReverse

httpwwwcode-kingsblogspotcom Page 18

static void Main(string[] args) reverseIt( I Am In Love With wwwcode-kingsblogspotcomcom) ConsoleWriteLine(nPress any key to continue) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 19

Named ArgumentsParameters in C

Named Arguments are an alternative way for specifing 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 specifiying 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

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 divisor5)

int a = remainder(divisor5 dividend 10)

Note that the position of the arguments have been interchanged both the above methods will

produce the same output ie they would set the value of a as 0(which is the remainder when

dividing 10 by 5)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 20

Optional ArgumentsParameters in C

This article will show you what is meant by Optional ArgumentsParameters in C 50 Optional

Arguments are mostly necessary when you specify functions that have a large number of

arguments

Optional Arguments are purely optional ie even if you do not specify them its perfectly OK

But it doesnt 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

The values that we supply in the function Definition are some constants These are the values

that are to be used in case no value is supplied in the function call These values are specified by

typing in variable expressions instead of just the declaration of variables

For example we would write

static void Func(Str = Default Value)

instead of static void Func(int Str)

If you didnt 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

When using this technique it is best that you have declared optional amp required parameters both

ie 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 = NA)

In the example above Name amp Age are required parameters The string Address is optional if

not specified then it would take the value NA meaning that 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)

Please Note

Do not Copy amp Paste code written here instead type it in your Development

Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 21

Transpose a Matrix

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

details

using System using SystemText using SystemThreadingTasks 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] ConsoleWriteLine(Enter the number of rows and columns of matrix ) m = ConvertToInt16(ConsoleReadLine()) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(Enter the elements of matrix n) for (c = 0 c lt m c++) for (d = 0 d lt n d++) matrix[c d] = ConvertToInt16(ConsoleReadLine()) for (c = 0 c lt m c++) for (d = 0 d lt n d++) transpose[d c] = matrix[c d]

httpwwwcode-kingsblogspotcom Page 22

ConsoleWriteLine(Transpose of entered matrix) for (c = 0 c lt n c++) for (d = 0 d lt m d++) ConsoleWrite( + transpose[c d]) ConsoleWriteLine() ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 23

Fibonacci Series

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 amp 1 The series goes on like

this

01123581321345589144233377helliphellip

Here we illustrate two techniques for the creation of the Fibonacci Series to n terms The For

Loop method amp 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 amp Second) Then we calculate the next term by adding these two terms amp setting a

new set of two new terms These terms are the Second amp Newest

using System using SystemText using SystemThreadingTasks namespace Fibonacci_series_Using_For_Loop class Program static void Main(string[] args) int n first = 0 second = 1 next c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First + n + terms of Fibonacci series are) for (c = 0 c lt n c++) if (c lt= 1) next = c

httpwwwcode-kingsblogspotcom Page 24

else next = first + second first = second second = next ConsoleWriteLine(next) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 25

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 amp two less than the number supplied In this way final

output value has each number added twice excluding 0 amp 1 Check the program below

using System using SystemText using SystemThreadingTasks namespace Fibonacci_Series_Recursion class Program static void Main(string[] args) int n i = 0 c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First 5 terms of Fibonacci series are) for (c = 1 c lt= n c++) ConsoleWriteLine(Fibonacci(i)) i++ ConsoleReadKey() static int Fibonacci(int n) if (n == 0) return 0 else if (n == 1) return 1 else return (Fibonacci(n - 1) + Fibonacci(n - 2))

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 26

Get Date Difference in C

Getting differences in two given dates is as easy as it gets The function used here is the

End_DateSubtract(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

using System using SystemText namespace Print_and_Get_Date_Difference_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) ConsoleWriteLine(The Date Today Is) DateTime DT = new DateTime() DT = DateTimeTodayDate ConsoleWriteLine(DTDateToString()) ConsoleWriteLine(Calculate the difference between two datesn) int year month day ConsoleWriteLine(Enter Start Date) ConsoleWriteLine(Enter Year)

httpwwwcode-kingsblogspotcom Page 27

year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_Start = new DateTime(yearmonthday) ConsoleWriteLine(nEnter End Date) ConsoleWriteLine(Enter Year) year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_End = new DateTime(year month day) TimeSpan timespan = DT_EndSubtract(DT_Start) ConsoleWriteLine(nThe Difference isn) ConsoleWriteLine(timespanTotalDaysToString() + Daysn) ConsoleWriteLine((timespanTotalDays 365)ToString() + Years) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 28

Obtain Local Host IP in C

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 SystemNet

namespace Obtain_IP_Address_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) String StringHost if (argsLength == 0) Getting Ip address of local machine First get the host name of local machine StringHost = SystemNetDnsGetHostName() ConsoleWriteLine(Local Machine Host Name is + StringHost) ConsoleWriteLine() else StringHost = args[0]

httpwwwcode-kingsblogspotcom Page 29

Then using host name get the IP address list IPHostEntry ipEntry = SystemNetDnsGetHostEntry(StringHost) IPAddress[] address = ipEntryAddressList for (int i = 0 i lt addressLength i++) ConsoleWriteLine() ConsoleWriteLine(IP Address Type 0 1 i address[i]ToString()) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 30

Monitor Turn OnOffStandBy in C

You might want to change your display settings in a running program The code behind requires

the Import of a Dll amp execution of a function SendMessage() by supplying 4 parameters The

value of the fourth parameter having values 0 1 amp 2 has the monitor in the states ON STAND

BY amp 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 SystemWindowsForms using SystemRuntimeInteropServices namespace Turn_Off_Monitor public partial class Form1 Form public Form1() InitializeComponent() [DllImport(user32dll)] public static extern IntPtr SendMessage(IntPtr hWnd uint 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(thisHandle WM_SYSCOMMAND b a) private void btnMonitorOff_Click(object sender EventArgs e) IntPtr a = new IntPtr(2) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

httpwwwcode-kingsblogspotcom Page 31

private void btnMonitorOn_Click(object sender EventArgs e) IntPtr a = new IntPtr(-1) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 32

Search Techniques Linear amp Binary

Searching is needed when we have a large array of some data or objects amp 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 amp finds the

position of elements Below you will find two search techniques viz Linear Search amp Binary

Search implemented in C The code is simple amp easy to understand amp can be modified as per

need

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 33

Code for Linear Search Technique in C Sharp

using System

using SystemText

using SystemThreadingTasks

namespace Linear_Search

class Program

static void Main(string[] args)

Int16[] array = new Int16[100]

Int16 search c number

ConsoleWriteLine(Enter the number of elements in arrayn)

number = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + numberToString() + numbersn)

for (c = 0 c lt number c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter the number to searchn)

search = ConvertToInt16(ConsoleReadLine())

for (c = 0 c lt number c++)

if (array[c] == search) if required element found

ConsoleWriteLine(searchToString() + is at locn + (c + 1)ToString() + n)

break

if (c == number)

ConsoleWriteLine(searchToString() + is not present in arrayn)

ConsoleReadLine()

httpwwwcode-kingsblogspotcom Page 34

Code for Binary Search Technique in C Sharp

namespace Binary_Search

class Program

static void Main(string[] args)

int c first last middle n search

Int16[] array = new Int16[100]

ConsoleWriteLine(Enter number of elementsn)

n = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + nToString() + integersn)

for (c = 0 c lt n c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter value to findn)

search = ConvertToInt16(ConsoleReadLine())

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

while (first lt= last)

if (array[middle] lt search)

first = middle + 1

else if (array[middle] == search)

ConsoleWriteLine(search + found at location + (middle + 1))

break

else

last = middle - 1

middle = (first + last) 2

if (first gt last)

ConsoleWriteLine(Not found + search + is not present in the list)

httpwwwcode-kingsblogspotcom Page 35

Working With Strings The 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 amp 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 txtLengthText = textBoxTextLengthToString() trkBar1Maximum = textBoxTextLength private void trackBar1_Scroll(object sender EventArgs e) Set the Max Value of second TrackBar trkBar2Maximum = textBoxTextLength - trkBar1Value textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString()

httpwwwcode-kingsblogspotcom Page 36

txtTotCharsText = trkBar2ValueToString() textBoxSelect()

Let us understand the working of this property with a simple String ABCDEFGH Suppose

you wanted to select the characters from between B amp C and Between F amp 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 ie

include A as well in the selection

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 ie a reduced

Maximum value

private void trackBar2_Scroll(object sender EventArgs e) textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString() txtTotCharsText = trkBar2ValueToString()

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 2: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 2

Hello World Program For 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 enabledthe 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 public FrmHelloWorld() InitializeComponent() private void timer1_Tick(object sender EventArgs e) lblWorldvisible = false lblHelloVisible = true timer1Enabled = false timer2Enabled = true

httpwwwcode-kingsblogspotcom Page 3

private void timer2_Tick(object sender EventArgs e) lblHelloVisible = false lblWorldVisible = true timer2Enabled = false timer1Enabled = true

private void cmdClickHere_Click(object sender EventArgs e) if (cmdClickHereText = Click Here ) timer1Enabled = true cmdClickHereText = STOP else if (cmdClickHereText = STOP ) timer1Enabled = false timer2Enabled = false cmdClickHereText = Click Here

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 4

An Advanced Calculator in C

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 +-

sincostan Of course there is no limit to the ways in which we can combine these and create

even more complex formulas The calculator stores different calculations in different textboxes

also showing the operands 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 must 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 ConvertToInt32() which converts its

httpwwwcode-kingsblogspotcom Page 5

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) txtAdditionText = txtXText + + + txtYText + = +

ConvertToString(ConvertToInt32((ConvertToInt32(txtXText))+(ConvertToInt3

2(txtYText))))

private void Subtraction_Click(object sender EventArgs e) txtSubtractionText = txtXText + - + txtYText + = +

ConvertToString(ConvertToInt32((ConvertToInt32(txtXText)) -

(ConvertToInt32(txtYText))))

private void Multiplication_Click(object sender EventArgs e) txtMultiplicationText = txtXText + + txtYText + = +

ConvertToString(ConvertToInt32((ConvertToInt32(txtXText))

(ConvertToInt32(txtYText))))

private void Division_Click(object sender EventArgs e) txtDivisionText = txtXText + + txtYText + = +

ConvertToString(ConvertToInt32((ConvertToInt32(txtXText))

(ConvertToInt32(txtYText))))

private void SinX_Click(object sender EventArgs e) txtSinXText = Sin +txtXText + = +

ConvertToString(MathSin(ConvertToDouble(txtXText))) private void CosX_Click(object sender EventArgs e) txtCosXText = Cos + txtXText + = +

ConvertToString(MathCos(ConvertToDouble(txtXText)))

httpwwwcode-kingsblogspotcom Page 6

private void TanX_Click(object sender EventArgs e) txtTanXText = Tan + txtXText + = +

ConvertToString(MathTan(ConvertToDouble(txtXText)))

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 7

Create Controls at Runtime in C 5

Sometimes you might want to create a user control at runtime There are times when you are not

sure of what controls to include during the designing phase of your forms In these cases what

usally is done is that we draw all available controls in the designer and at runtime we simply

make the controls invisible during runtime leaving us with workable visible controls But this is

not the right method What should be done is exactly illustrated below You should draw the

controls at runtime Yes you should draw the controls only 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 method to create them If you look carefully in the

Designer of any form you will find codes that initiate the creation of controls You will see some

properties set leaving other properties default And this is exactly what we are doing here We

are writing code behinf the Fom that creates the controls with some properties set by ourselves amp

others are simply set to their default value by the Compiler

The main steps to draw controls are summarized below

CreateDefine the control or Array of controls

Set the properties of the control or individual controls in case of Arrays

Add the controls to the form or other parent containers such as Panels

Call the Show() method to display the control

Thats it

httpwwwcode-kingsblogspotcom Page 8

The code below shows how to draw controls

namespace CreateControlsAtRuntime 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 lt= 6 i++) tb[i] = new TextBox() tb[i]Width = 150 tb[i]Left = 20 tb[i]Top = (30 i) + 30 tb[i]Text = Text Box Number + iToString() thisControlsAdd(tb[i]) tb[i]Show()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 9

Check for Anagrams in Net C

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 for 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 lt aLength c++) first[a[c] - a]++ c = 0 for (c=0 cltbLength c++) second[b[c] - a]++ for (c = 0 c lt 26 c++) if (first[c] = second[c]) return 0 return 1

httpwwwcode-kingsblogspotcom Page 10

using System namespace Anagram_Test class Program static void Main(string[] args) ClassCheckAnagram cca = new ClassCheckAnagram() ConsoleWriteLine(Enter first stringn) string aa = ConsoleReadLine() char[] a = aaToCharArray() ConsoleWriteLine(nEnter second stringn) string bb = ConsoleReadLine() char[] b = bbToCharArray() int flag = ccacheck_anagram(a b) if (flag == 1) ConsoleWriteLine(nThey are anagramsn) else ConsoleWriteLine(nThey are not anagramsn) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 11

Using Indexers in C 5

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

obj1RollNumberVariable[0] obj1RollNumberVariable[1]

where RollNumberVariable would be the Integer variable

Now that you have learnt how to index your class amp 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 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 lt size i++) RollNumberVariable[i] = 0

httpwwwcode-kingsblogspotcom Page 12

public Int16 this[int pos] get return RollNumberVariable[pos] set RollNumberVariable[pos] = value using System namespace Indexers_Example class Program static void Main(string[] args) Int16 size = 5 Indexers obj1 = new Indexers(size) for (int i = 0 i lt size i++) obj1[i] = (short)i ConsoleWriteLine(nIndexer Outputn) for (int i = 0 i lt size i++) ConsoleWriteLine(Next Roll No + obj1[i]) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 13

How to Write into Windows Registry in C

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 as shown below

The Keys at the parent level are HKEY_CLASSES_ROOT HKEY_CURRENT_USER etc When we refer to

these keys in our C program code we omit the HKEY amp the underscores So to refer to the

HKEY_CURRENT_USER we use simply CurrentUser as the reference Well this reference is available

from the MicrosoftWin32Registry class This Registry class is available through the reference

using MicrosoftWin32

We use this reference to create a Key object An example of a Key object would be

MicrosoftWin32RegistryKey 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 = MicrosoftWin32RegistryClassesRootCreateSubKey(CSharp_Website)

Next we can set the Value of this Field using the SetValue() funtion See below

keySetValue(Really Yes)

httpwwwcode-kingsblogspotcom Page 14

The output shown below

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 15

Convert From Decimal to Binary System

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 gtgt

using System

namespace convert_decimal_to_binary

class Program

static void Main(string[] args)

int n c k

ConsoleWriteLine(Enter an integer in Decimal number systemn)

n = ConvertToInt32(ConsoleReadLine())

ConsoleWriteLine(nBinary Equivalent isn)

for (c = 31 c gt= 0 c--)

k = n gtgt c

if (ConvertToBoolean(k amp 1))

ConsoleWrite(1)

else

ConsoleWrite(0)

ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 16

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 TraceWriteLine() 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)

TraceWriteLine(message + message)

TraceWriteLine(member name + memberName)

TraceWriteLine(source file path + sourceFilePath)

TraceWriteLine(source line number + sourceLineNumber)

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

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 17

Reverse the Words in a Given 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 = strSourceSplit(new char[] ) string strReverse = stringEmpty for (int i = arySourceLength - 1 i gt= 0 i--) strReverse = strReverse + + arySource[i] ConsoleWriteLine(Original String nn + strSource) ConsoleWriteLine(nnReversed String nn + strReverse) return strReverse

httpwwwcode-kingsblogspotcom Page 18

static void Main(string[] args) reverseIt( I Am In Love With wwwcode-kingsblogspotcomcom) ConsoleWriteLine(nPress any key to continue) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 19

Named ArgumentsParameters in C

Named Arguments are an alternative way for specifing 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 specifiying 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

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 divisor5)

int a = remainder(divisor5 dividend 10)

Note that the position of the arguments have been interchanged both the above methods will

produce the same output ie they would set the value of a as 0(which is the remainder when

dividing 10 by 5)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 20

Optional ArgumentsParameters in C

This article will show you what is meant by Optional ArgumentsParameters in C 50 Optional

Arguments are mostly necessary when you specify functions that have a large number of

arguments

Optional Arguments are purely optional ie even if you do not specify them its perfectly OK

But it doesnt 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

The values that we supply in the function Definition are some constants These are the values

that are to be used in case no value is supplied in the function call These values are specified by

typing in variable expressions instead of just the declaration of variables

For example we would write

static void Func(Str = Default Value)

instead of static void Func(int Str)

If you didnt 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

When using this technique it is best that you have declared optional amp required parameters both

ie 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 = NA)

In the example above Name amp Age are required parameters The string Address is optional if

not specified then it would take the value NA meaning that 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)

Please Note

Do not Copy amp Paste code written here instead type it in your Development

Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 21

Transpose a Matrix

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

details

using System using SystemText using SystemThreadingTasks 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] ConsoleWriteLine(Enter the number of rows and columns of matrix ) m = ConvertToInt16(ConsoleReadLine()) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(Enter the elements of matrix n) for (c = 0 c lt m c++) for (d = 0 d lt n d++) matrix[c d] = ConvertToInt16(ConsoleReadLine()) for (c = 0 c lt m c++) for (d = 0 d lt n d++) transpose[d c] = matrix[c d]

httpwwwcode-kingsblogspotcom Page 22

ConsoleWriteLine(Transpose of entered matrix) for (c = 0 c lt n c++) for (d = 0 d lt m d++) ConsoleWrite( + transpose[c d]) ConsoleWriteLine() ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 23

Fibonacci Series

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 amp 1 The series goes on like

this

01123581321345589144233377helliphellip

Here we illustrate two techniques for the creation of the Fibonacci Series to n terms The For

Loop method amp 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 amp Second) Then we calculate the next term by adding these two terms amp setting a

new set of two new terms These terms are the Second amp Newest

using System using SystemText using SystemThreadingTasks namespace Fibonacci_series_Using_For_Loop class Program static void Main(string[] args) int n first = 0 second = 1 next c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First + n + terms of Fibonacci series are) for (c = 0 c lt n c++) if (c lt= 1) next = c

httpwwwcode-kingsblogspotcom Page 24

else next = first + second first = second second = next ConsoleWriteLine(next) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 25

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 amp two less than the number supplied In this way final

output value has each number added twice excluding 0 amp 1 Check the program below

using System using SystemText using SystemThreadingTasks namespace Fibonacci_Series_Recursion class Program static void Main(string[] args) int n i = 0 c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First 5 terms of Fibonacci series are) for (c = 1 c lt= n c++) ConsoleWriteLine(Fibonacci(i)) i++ ConsoleReadKey() static int Fibonacci(int n) if (n == 0) return 0 else if (n == 1) return 1 else return (Fibonacci(n - 1) + Fibonacci(n - 2))

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 26

Get Date Difference in C

Getting differences in two given dates is as easy as it gets The function used here is the

End_DateSubtract(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

using System using SystemText namespace Print_and_Get_Date_Difference_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) ConsoleWriteLine(The Date Today Is) DateTime DT = new DateTime() DT = DateTimeTodayDate ConsoleWriteLine(DTDateToString()) ConsoleWriteLine(Calculate the difference between two datesn) int year month day ConsoleWriteLine(Enter Start Date) ConsoleWriteLine(Enter Year)

httpwwwcode-kingsblogspotcom Page 27

year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_Start = new DateTime(yearmonthday) ConsoleWriteLine(nEnter End Date) ConsoleWriteLine(Enter Year) year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_End = new DateTime(year month day) TimeSpan timespan = DT_EndSubtract(DT_Start) ConsoleWriteLine(nThe Difference isn) ConsoleWriteLine(timespanTotalDaysToString() + Daysn) ConsoleWriteLine((timespanTotalDays 365)ToString() + Years) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 28

Obtain Local Host IP in C

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 SystemNet

namespace Obtain_IP_Address_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) String StringHost if (argsLength == 0) Getting Ip address of local machine First get the host name of local machine StringHost = SystemNetDnsGetHostName() ConsoleWriteLine(Local Machine Host Name is + StringHost) ConsoleWriteLine() else StringHost = args[0]

httpwwwcode-kingsblogspotcom Page 29

Then using host name get the IP address list IPHostEntry ipEntry = SystemNetDnsGetHostEntry(StringHost) IPAddress[] address = ipEntryAddressList for (int i = 0 i lt addressLength i++) ConsoleWriteLine() ConsoleWriteLine(IP Address Type 0 1 i address[i]ToString()) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 30

Monitor Turn OnOffStandBy in C

You might want to change your display settings in a running program The code behind requires

the Import of a Dll amp execution of a function SendMessage() by supplying 4 parameters The

value of the fourth parameter having values 0 1 amp 2 has the monitor in the states ON STAND

BY amp 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 SystemWindowsForms using SystemRuntimeInteropServices namespace Turn_Off_Monitor public partial class Form1 Form public Form1() InitializeComponent() [DllImport(user32dll)] public static extern IntPtr SendMessage(IntPtr hWnd uint 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(thisHandle WM_SYSCOMMAND b a) private void btnMonitorOff_Click(object sender EventArgs e) IntPtr a = new IntPtr(2) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

httpwwwcode-kingsblogspotcom Page 31

private void btnMonitorOn_Click(object sender EventArgs e) IntPtr a = new IntPtr(-1) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 32

Search Techniques Linear amp Binary

Searching is needed when we have a large array of some data or objects amp 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 amp finds the

position of elements Below you will find two search techniques viz Linear Search amp Binary

Search implemented in C The code is simple amp easy to understand amp can be modified as per

need

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 33

Code for Linear Search Technique in C Sharp

using System

using SystemText

using SystemThreadingTasks

namespace Linear_Search

class Program

static void Main(string[] args)

Int16[] array = new Int16[100]

Int16 search c number

ConsoleWriteLine(Enter the number of elements in arrayn)

number = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + numberToString() + numbersn)

for (c = 0 c lt number c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter the number to searchn)

search = ConvertToInt16(ConsoleReadLine())

for (c = 0 c lt number c++)

if (array[c] == search) if required element found

ConsoleWriteLine(searchToString() + is at locn + (c + 1)ToString() + n)

break

if (c == number)

ConsoleWriteLine(searchToString() + is not present in arrayn)

ConsoleReadLine()

httpwwwcode-kingsblogspotcom Page 34

Code for Binary Search Technique in C Sharp

namespace Binary_Search

class Program

static void Main(string[] args)

int c first last middle n search

Int16[] array = new Int16[100]

ConsoleWriteLine(Enter number of elementsn)

n = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + nToString() + integersn)

for (c = 0 c lt n c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter value to findn)

search = ConvertToInt16(ConsoleReadLine())

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

while (first lt= last)

if (array[middle] lt search)

first = middle + 1

else if (array[middle] == search)

ConsoleWriteLine(search + found at location + (middle + 1))

break

else

last = middle - 1

middle = (first + last) 2

if (first gt last)

ConsoleWriteLine(Not found + search + is not present in the list)

httpwwwcode-kingsblogspotcom Page 35

Working With Strings The 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 amp 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 txtLengthText = textBoxTextLengthToString() trkBar1Maximum = textBoxTextLength private void trackBar1_Scroll(object sender EventArgs e) Set the Max Value of second TrackBar trkBar2Maximum = textBoxTextLength - trkBar1Value textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString()

httpwwwcode-kingsblogspotcom Page 36

txtTotCharsText = trkBar2ValueToString() textBoxSelect()

Let us understand the working of this property with a simple String ABCDEFGH Suppose

you wanted to select the characters from between B amp C and Between F amp 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 ie

include A as well in the selection

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 ie a reduced

Maximum value

private void trackBar2_Scroll(object sender EventArgs e) textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString() txtTotCharsText = trkBar2ValueToString()

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 3: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 3

private void timer2_Tick(object sender EventArgs e) lblHelloVisible = false lblWorldVisible = true timer2Enabled = false timer1Enabled = true

private void cmdClickHere_Click(object sender EventArgs e) if (cmdClickHereText = Click Here ) timer1Enabled = true cmdClickHereText = STOP else if (cmdClickHereText = STOP ) timer1Enabled = false timer2Enabled = false cmdClickHereText = Click Here

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 4

An Advanced Calculator in C

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 +-

sincostan Of course there is no limit to the ways in which we can combine these and create

even more complex formulas The calculator stores different calculations in different textboxes

also showing the operands 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 must 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 ConvertToInt32() which converts its

httpwwwcode-kingsblogspotcom Page 5

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) txtAdditionText = txtXText + + + txtYText + = +

ConvertToString(ConvertToInt32((ConvertToInt32(txtXText))+(ConvertToInt3

2(txtYText))))

private void Subtraction_Click(object sender EventArgs e) txtSubtractionText = txtXText + - + txtYText + = +

ConvertToString(ConvertToInt32((ConvertToInt32(txtXText)) -

(ConvertToInt32(txtYText))))

private void Multiplication_Click(object sender EventArgs e) txtMultiplicationText = txtXText + + txtYText + = +

ConvertToString(ConvertToInt32((ConvertToInt32(txtXText))

(ConvertToInt32(txtYText))))

private void Division_Click(object sender EventArgs e) txtDivisionText = txtXText + + txtYText + = +

ConvertToString(ConvertToInt32((ConvertToInt32(txtXText))

(ConvertToInt32(txtYText))))

private void SinX_Click(object sender EventArgs e) txtSinXText = Sin +txtXText + = +

ConvertToString(MathSin(ConvertToDouble(txtXText))) private void CosX_Click(object sender EventArgs e) txtCosXText = Cos + txtXText + = +

ConvertToString(MathCos(ConvertToDouble(txtXText)))

httpwwwcode-kingsblogspotcom Page 6

private void TanX_Click(object sender EventArgs e) txtTanXText = Tan + txtXText + = +

ConvertToString(MathTan(ConvertToDouble(txtXText)))

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 7

Create Controls at Runtime in C 5

Sometimes you might want to create a user control at runtime There are times when you are not

sure of what controls to include during the designing phase of your forms In these cases what

usally is done is that we draw all available controls in the designer and at runtime we simply

make the controls invisible during runtime leaving us with workable visible controls But this is

not the right method What should be done is exactly illustrated below You should draw the

controls at runtime Yes you should draw the controls only 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 method to create them If you look carefully in the

Designer of any form you will find codes that initiate the creation of controls You will see some

properties set leaving other properties default And this is exactly what we are doing here We

are writing code behinf the Fom that creates the controls with some properties set by ourselves amp

others are simply set to their default value by the Compiler

The main steps to draw controls are summarized below

CreateDefine the control or Array of controls

Set the properties of the control or individual controls in case of Arrays

Add the controls to the form or other parent containers such as Panels

Call the Show() method to display the control

Thats it

httpwwwcode-kingsblogspotcom Page 8

The code below shows how to draw controls

namespace CreateControlsAtRuntime 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 lt= 6 i++) tb[i] = new TextBox() tb[i]Width = 150 tb[i]Left = 20 tb[i]Top = (30 i) + 30 tb[i]Text = Text Box Number + iToString() thisControlsAdd(tb[i]) tb[i]Show()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 9

Check for Anagrams in Net C

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 for 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 lt aLength c++) first[a[c] - a]++ c = 0 for (c=0 cltbLength c++) second[b[c] - a]++ for (c = 0 c lt 26 c++) if (first[c] = second[c]) return 0 return 1

httpwwwcode-kingsblogspotcom Page 10

using System namespace Anagram_Test class Program static void Main(string[] args) ClassCheckAnagram cca = new ClassCheckAnagram() ConsoleWriteLine(Enter first stringn) string aa = ConsoleReadLine() char[] a = aaToCharArray() ConsoleWriteLine(nEnter second stringn) string bb = ConsoleReadLine() char[] b = bbToCharArray() int flag = ccacheck_anagram(a b) if (flag == 1) ConsoleWriteLine(nThey are anagramsn) else ConsoleWriteLine(nThey are not anagramsn) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 11

Using Indexers in C 5

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

obj1RollNumberVariable[0] obj1RollNumberVariable[1]

where RollNumberVariable would be the Integer variable

Now that you have learnt how to index your class amp 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 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 lt size i++) RollNumberVariable[i] = 0

httpwwwcode-kingsblogspotcom Page 12

public Int16 this[int pos] get return RollNumberVariable[pos] set RollNumberVariable[pos] = value using System namespace Indexers_Example class Program static void Main(string[] args) Int16 size = 5 Indexers obj1 = new Indexers(size) for (int i = 0 i lt size i++) obj1[i] = (short)i ConsoleWriteLine(nIndexer Outputn) for (int i = 0 i lt size i++) ConsoleWriteLine(Next Roll No + obj1[i]) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 13

How to Write into Windows Registry in C

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 as shown below

The Keys at the parent level are HKEY_CLASSES_ROOT HKEY_CURRENT_USER etc When we refer to

these keys in our C program code we omit the HKEY amp the underscores So to refer to the

HKEY_CURRENT_USER we use simply CurrentUser as the reference Well this reference is available

from the MicrosoftWin32Registry class This Registry class is available through the reference

using MicrosoftWin32

We use this reference to create a Key object An example of a Key object would be

MicrosoftWin32RegistryKey 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 = MicrosoftWin32RegistryClassesRootCreateSubKey(CSharp_Website)

Next we can set the Value of this Field using the SetValue() funtion See below

keySetValue(Really Yes)

httpwwwcode-kingsblogspotcom Page 14

The output shown below

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 15

Convert From Decimal to Binary System

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 gtgt

using System

namespace convert_decimal_to_binary

class Program

static void Main(string[] args)

int n c k

ConsoleWriteLine(Enter an integer in Decimal number systemn)

n = ConvertToInt32(ConsoleReadLine())

ConsoleWriteLine(nBinary Equivalent isn)

for (c = 31 c gt= 0 c--)

k = n gtgt c

if (ConvertToBoolean(k amp 1))

ConsoleWrite(1)

else

ConsoleWrite(0)

ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 16

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 TraceWriteLine() 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)

TraceWriteLine(message + message)

TraceWriteLine(member name + memberName)

TraceWriteLine(source file path + sourceFilePath)

TraceWriteLine(source line number + sourceLineNumber)

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

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 17

Reverse the Words in a Given 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 = strSourceSplit(new char[] ) string strReverse = stringEmpty for (int i = arySourceLength - 1 i gt= 0 i--) strReverse = strReverse + + arySource[i] ConsoleWriteLine(Original String nn + strSource) ConsoleWriteLine(nnReversed String nn + strReverse) return strReverse

httpwwwcode-kingsblogspotcom Page 18

static void Main(string[] args) reverseIt( I Am In Love With wwwcode-kingsblogspotcomcom) ConsoleWriteLine(nPress any key to continue) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 19

Named ArgumentsParameters in C

Named Arguments are an alternative way for specifing 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 specifiying 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

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 divisor5)

int a = remainder(divisor5 dividend 10)

Note that the position of the arguments have been interchanged both the above methods will

produce the same output ie they would set the value of a as 0(which is the remainder when

dividing 10 by 5)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 20

Optional ArgumentsParameters in C

This article will show you what is meant by Optional ArgumentsParameters in C 50 Optional

Arguments are mostly necessary when you specify functions that have a large number of

arguments

Optional Arguments are purely optional ie even if you do not specify them its perfectly OK

But it doesnt 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

The values that we supply in the function Definition are some constants These are the values

that are to be used in case no value is supplied in the function call These values are specified by

typing in variable expressions instead of just the declaration of variables

For example we would write

static void Func(Str = Default Value)

instead of static void Func(int Str)

If you didnt 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

When using this technique it is best that you have declared optional amp required parameters both

ie 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 = NA)

In the example above Name amp Age are required parameters The string Address is optional if

not specified then it would take the value NA meaning that 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)

Please Note

Do not Copy amp Paste code written here instead type it in your Development

Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 21

Transpose a Matrix

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

details

using System using SystemText using SystemThreadingTasks 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] ConsoleWriteLine(Enter the number of rows and columns of matrix ) m = ConvertToInt16(ConsoleReadLine()) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(Enter the elements of matrix n) for (c = 0 c lt m c++) for (d = 0 d lt n d++) matrix[c d] = ConvertToInt16(ConsoleReadLine()) for (c = 0 c lt m c++) for (d = 0 d lt n d++) transpose[d c] = matrix[c d]

httpwwwcode-kingsblogspotcom Page 22

ConsoleWriteLine(Transpose of entered matrix) for (c = 0 c lt n c++) for (d = 0 d lt m d++) ConsoleWrite( + transpose[c d]) ConsoleWriteLine() ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 23

Fibonacci Series

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 amp 1 The series goes on like

this

01123581321345589144233377helliphellip

Here we illustrate two techniques for the creation of the Fibonacci Series to n terms The For

Loop method amp 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 amp Second) Then we calculate the next term by adding these two terms amp setting a

new set of two new terms These terms are the Second amp Newest

using System using SystemText using SystemThreadingTasks namespace Fibonacci_series_Using_For_Loop class Program static void Main(string[] args) int n first = 0 second = 1 next c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First + n + terms of Fibonacci series are) for (c = 0 c lt n c++) if (c lt= 1) next = c

httpwwwcode-kingsblogspotcom Page 24

else next = first + second first = second second = next ConsoleWriteLine(next) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 25

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 amp two less than the number supplied In this way final

output value has each number added twice excluding 0 amp 1 Check the program below

using System using SystemText using SystemThreadingTasks namespace Fibonacci_Series_Recursion class Program static void Main(string[] args) int n i = 0 c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First 5 terms of Fibonacci series are) for (c = 1 c lt= n c++) ConsoleWriteLine(Fibonacci(i)) i++ ConsoleReadKey() static int Fibonacci(int n) if (n == 0) return 0 else if (n == 1) return 1 else return (Fibonacci(n - 1) + Fibonacci(n - 2))

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 26

Get Date Difference in C

Getting differences in two given dates is as easy as it gets The function used here is the

End_DateSubtract(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

using System using SystemText namespace Print_and_Get_Date_Difference_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) ConsoleWriteLine(The Date Today Is) DateTime DT = new DateTime() DT = DateTimeTodayDate ConsoleWriteLine(DTDateToString()) ConsoleWriteLine(Calculate the difference between two datesn) int year month day ConsoleWriteLine(Enter Start Date) ConsoleWriteLine(Enter Year)

httpwwwcode-kingsblogspotcom Page 27

year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_Start = new DateTime(yearmonthday) ConsoleWriteLine(nEnter End Date) ConsoleWriteLine(Enter Year) year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_End = new DateTime(year month day) TimeSpan timespan = DT_EndSubtract(DT_Start) ConsoleWriteLine(nThe Difference isn) ConsoleWriteLine(timespanTotalDaysToString() + Daysn) ConsoleWriteLine((timespanTotalDays 365)ToString() + Years) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 28

Obtain Local Host IP in C

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 SystemNet

namespace Obtain_IP_Address_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) String StringHost if (argsLength == 0) Getting Ip address of local machine First get the host name of local machine StringHost = SystemNetDnsGetHostName() ConsoleWriteLine(Local Machine Host Name is + StringHost) ConsoleWriteLine() else StringHost = args[0]

httpwwwcode-kingsblogspotcom Page 29

Then using host name get the IP address list IPHostEntry ipEntry = SystemNetDnsGetHostEntry(StringHost) IPAddress[] address = ipEntryAddressList for (int i = 0 i lt addressLength i++) ConsoleWriteLine() ConsoleWriteLine(IP Address Type 0 1 i address[i]ToString()) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 30

Monitor Turn OnOffStandBy in C

You might want to change your display settings in a running program The code behind requires

the Import of a Dll amp execution of a function SendMessage() by supplying 4 parameters The

value of the fourth parameter having values 0 1 amp 2 has the monitor in the states ON STAND

BY amp 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 SystemWindowsForms using SystemRuntimeInteropServices namespace Turn_Off_Monitor public partial class Form1 Form public Form1() InitializeComponent() [DllImport(user32dll)] public static extern IntPtr SendMessage(IntPtr hWnd uint 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(thisHandle WM_SYSCOMMAND b a) private void btnMonitorOff_Click(object sender EventArgs e) IntPtr a = new IntPtr(2) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

httpwwwcode-kingsblogspotcom Page 31

private void btnMonitorOn_Click(object sender EventArgs e) IntPtr a = new IntPtr(-1) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 32

Search Techniques Linear amp Binary

Searching is needed when we have a large array of some data or objects amp 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 amp finds the

position of elements Below you will find two search techniques viz Linear Search amp Binary

Search implemented in C The code is simple amp easy to understand amp can be modified as per

need

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 33

Code for Linear Search Technique in C Sharp

using System

using SystemText

using SystemThreadingTasks

namespace Linear_Search

class Program

static void Main(string[] args)

Int16[] array = new Int16[100]

Int16 search c number

ConsoleWriteLine(Enter the number of elements in arrayn)

number = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + numberToString() + numbersn)

for (c = 0 c lt number c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter the number to searchn)

search = ConvertToInt16(ConsoleReadLine())

for (c = 0 c lt number c++)

if (array[c] == search) if required element found

ConsoleWriteLine(searchToString() + is at locn + (c + 1)ToString() + n)

break

if (c == number)

ConsoleWriteLine(searchToString() + is not present in arrayn)

ConsoleReadLine()

httpwwwcode-kingsblogspotcom Page 34

Code for Binary Search Technique in C Sharp

namespace Binary_Search

class Program

static void Main(string[] args)

int c first last middle n search

Int16[] array = new Int16[100]

ConsoleWriteLine(Enter number of elementsn)

n = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + nToString() + integersn)

for (c = 0 c lt n c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter value to findn)

search = ConvertToInt16(ConsoleReadLine())

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

while (first lt= last)

if (array[middle] lt search)

first = middle + 1

else if (array[middle] == search)

ConsoleWriteLine(search + found at location + (middle + 1))

break

else

last = middle - 1

middle = (first + last) 2

if (first gt last)

ConsoleWriteLine(Not found + search + is not present in the list)

httpwwwcode-kingsblogspotcom Page 35

Working With Strings The 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 amp 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 txtLengthText = textBoxTextLengthToString() trkBar1Maximum = textBoxTextLength private void trackBar1_Scroll(object sender EventArgs e) Set the Max Value of second TrackBar trkBar2Maximum = textBoxTextLength - trkBar1Value textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString()

httpwwwcode-kingsblogspotcom Page 36

txtTotCharsText = trkBar2ValueToString() textBoxSelect()

Let us understand the working of this property with a simple String ABCDEFGH Suppose

you wanted to select the characters from between B amp C and Between F amp 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 ie

include A as well in the selection

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 ie a reduced

Maximum value

private void trackBar2_Scroll(object sender EventArgs e) textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString() txtTotCharsText = trkBar2ValueToString()

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 4: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 4

An Advanced Calculator in C

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 +-

sincostan Of course there is no limit to the ways in which we can combine these and create

even more complex formulas The calculator stores different calculations in different textboxes

also showing the operands 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 must 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 ConvertToInt32() which converts its

httpwwwcode-kingsblogspotcom Page 5

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) txtAdditionText = txtXText + + + txtYText + = +

ConvertToString(ConvertToInt32((ConvertToInt32(txtXText))+(ConvertToInt3

2(txtYText))))

private void Subtraction_Click(object sender EventArgs e) txtSubtractionText = txtXText + - + txtYText + = +

ConvertToString(ConvertToInt32((ConvertToInt32(txtXText)) -

(ConvertToInt32(txtYText))))

private void Multiplication_Click(object sender EventArgs e) txtMultiplicationText = txtXText + + txtYText + = +

ConvertToString(ConvertToInt32((ConvertToInt32(txtXText))

(ConvertToInt32(txtYText))))

private void Division_Click(object sender EventArgs e) txtDivisionText = txtXText + + txtYText + = +

ConvertToString(ConvertToInt32((ConvertToInt32(txtXText))

(ConvertToInt32(txtYText))))

private void SinX_Click(object sender EventArgs e) txtSinXText = Sin +txtXText + = +

ConvertToString(MathSin(ConvertToDouble(txtXText))) private void CosX_Click(object sender EventArgs e) txtCosXText = Cos + txtXText + = +

ConvertToString(MathCos(ConvertToDouble(txtXText)))

httpwwwcode-kingsblogspotcom Page 6

private void TanX_Click(object sender EventArgs e) txtTanXText = Tan + txtXText + = +

ConvertToString(MathTan(ConvertToDouble(txtXText)))

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 7

Create Controls at Runtime in C 5

Sometimes you might want to create a user control at runtime There are times when you are not

sure of what controls to include during the designing phase of your forms In these cases what

usally is done is that we draw all available controls in the designer and at runtime we simply

make the controls invisible during runtime leaving us with workable visible controls But this is

not the right method What should be done is exactly illustrated below You should draw the

controls at runtime Yes you should draw the controls only 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 method to create them If you look carefully in the

Designer of any form you will find codes that initiate the creation of controls You will see some

properties set leaving other properties default And this is exactly what we are doing here We

are writing code behinf the Fom that creates the controls with some properties set by ourselves amp

others are simply set to their default value by the Compiler

The main steps to draw controls are summarized below

CreateDefine the control or Array of controls

Set the properties of the control or individual controls in case of Arrays

Add the controls to the form or other parent containers such as Panels

Call the Show() method to display the control

Thats it

httpwwwcode-kingsblogspotcom Page 8

The code below shows how to draw controls

namespace CreateControlsAtRuntime 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 lt= 6 i++) tb[i] = new TextBox() tb[i]Width = 150 tb[i]Left = 20 tb[i]Top = (30 i) + 30 tb[i]Text = Text Box Number + iToString() thisControlsAdd(tb[i]) tb[i]Show()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 9

Check for Anagrams in Net C

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 for 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 lt aLength c++) first[a[c] - a]++ c = 0 for (c=0 cltbLength c++) second[b[c] - a]++ for (c = 0 c lt 26 c++) if (first[c] = second[c]) return 0 return 1

httpwwwcode-kingsblogspotcom Page 10

using System namespace Anagram_Test class Program static void Main(string[] args) ClassCheckAnagram cca = new ClassCheckAnagram() ConsoleWriteLine(Enter first stringn) string aa = ConsoleReadLine() char[] a = aaToCharArray() ConsoleWriteLine(nEnter second stringn) string bb = ConsoleReadLine() char[] b = bbToCharArray() int flag = ccacheck_anagram(a b) if (flag == 1) ConsoleWriteLine(nThey are anagramsn) else ConsoleWriteLine(nThey are not anagramsn) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 11

Using Indexers in C 5

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

obj1RollNumberVariable[0] obj1RollNumberVariable[1]

where RollNumberVariable would be the Integer variable

Now that you have learnt how to index your class amp 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 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 lt size i++) RollNumberVariable[i] = 0

httpwwwcode-kingsblogspotcom Page 12

public Int16 this[int pos] get return RollNumberVariable[pos] set RollNumberVariable[pos] = value using System namespace Indexers_Example class Program static void Main(string[] args) Int16 size = 5 Indexers obj1 = new Indexers(size) for (int i = 0 i lt size i++) obj1[i] = (short)i ConsoleWriteLine(nIndexer Outputn) for (int i = 0 i lt size i++) ConsoleWriteLine(Next Roll No + obj1[i]) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 13

How to Write into Windows Registry in C

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 as shown below

The Keys at the parent level are HKEY_CLASSES_ROOT HKEY_CURRENT_USER etc When we refer to

these keys in our C program code we omit the HKEY amp the underscores So to refer to the

HKEY_CURRENT_USER we use simply CurrentUser as the reference Well this reference is available

from the MicrosoftWin32Registry class This Registry class is available through the reference

using MicrosoftWin32

We use this reference to create a Key object An example of a Key object would be

MicrosoftWin32RegistryKey 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 = MicrosoftWin32RegistryClassesRootCreateSubKey(CSharp_Website)

Next we can set the Value of this Field using the SetValue() funtion See below

keySetValue(Really Yes)

httpwwwcode-kingsblogspotcom Page 14

The output shown below

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 15

Convert From Decimal to Binary System

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 gtgt

using System

namespace convert_decimal_to_binary

class Program

static void Main(string[] args)

int n c k

ConsoleWriteLine(Enter an integer in Decimal number systemn)

n = ConvertToInt32(ConsoleReadLine())

ConsoleWriteLine(nBinary Equivalent isn)

for (c = 31 c gt= 0 c--)

k = n gtgt c

if (ConvertToBoolean(k amp 1))

ConsoleWrite(1)

else

ConsoleWrite(0)

ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 16

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 TraceWriteLine() 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)

TraceWriteLine(message + message)

TraceWriteLine(member name + memberName)

TraceWriteLine(source file path + sourceFilePath)

TraceWriteLine(source line number + sourceLineNumber)

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

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 17

Reverse the Words in a Given 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 = strSourceSplit(new char[] ) string strReverse = stringEmpty for (int i = arySourceLength - 1 i gt= 0 i--) strReverse = strReverse + + arySource[i] ConsoleWriteLine(Original String nn + strSource) ConsoleWriteLine(nnReversed String nn + strReverse) return strReverse

httpwwwcode-kingsblogspotcom Page 18

static void Main(string[] args) reverseIt( I Am In Love With wwwcode-kingsblogspotcomcom) ConsoleWriteLine(nPress any key to continue) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 19

Named ArgumentsParameters in C

Named Arguments are an alternative way for specifing 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 specifiying 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

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 divisor5)

int a = remainder(divisor5 dividend 10)

Note that the position of the arguments have been interchanged both the above methods will

produce the same output ie they would set the value of a as 0(which is the remainder when

dividing 10 by 5)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 20

Optional ArgumentsParameters in C

This article will show you what is meant by Optional ArgumentsParameters in C 50 Optional

Arguments are mostly necessary when you specify functions that have a large number of

arguments

Optional Arguments are purely optional ie even if you do not specify them its perfectly OK

But it doesnt 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

The values that we supply in the function Definition are some constants These are the values

that are to be used in case no value is supplied in the function call These values are specified by

typing in variable expressions instead of just the declaration of variables

For example we would write

static void Func(Str = Default Value)

instead of static void Func(int Str)

If you didnt 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

When using this technique it is best that you have declared optional amp required parameters both

ie 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 = NA)

In the example above Name amp Age are required parameters The string Address is optional if

not specified then it would take the value NA meaning that 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)

Please Note

Do not Copy amp Paste code written here instead type it in your Development

Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 21

Transpose a Matrix

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

details

using System using SystemText using SystemThreadingTasks 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] ConsoleWriteLine(Enter the number of rows and columns of matrix ) m = ConvertToInt16(ConsoleReadLine()) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(Enter the elements of matrix n) for (c = 0 c lt m c++) for (d = 0 d lt n d++) matrix[c d] = ConvertToInt16(ConsoleReadLine()) for (c = 0 c lt m c++) for (d = 0 d lt n d++) transpose[d c] = matrix[c d]

httpwwwcode-kingsblogspotcom Page 22

ConsoleWriteLine(Transpose of entered matrix) for (c = 0 c lt n c++) for (d = 0 d lt m d++) ConsoleWrite( + transpose[c d]) ConsoleWriteLine() ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 23

Fibonacci Series

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 amp 1 The series goes on like

this

01123581321345589144233377helliphellip

Here we illustrate two techniques for the creation of the Fibonacci Series to n terms The For

Loop method amp 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 amp Second) Then we calculate the next term by adding these two terms amp setting a

new set of two new terms These terms are the Second amp Newest

using System using SystemText using SystemThreadingTasks namespace Fibonacci_series_Using_For_Loop class Program static void Main(string[] args) int n first = 0 second = 1 next c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First + n + terms of Fibonacci series are) for (c = 0 c lt n c++) if (c lt= 1) next = c

httpwwwcode-kingsblogspotcom Page 24

else next = first + second first = second second = next ConsoleWriteLine(next) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 25

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 amp two less than the number supplied In this way final

output value has each number added twice excluding 0 amp 1 Check the program below

using System using SystemText using SystemThreadingTasks namespace Fibonacci_Series_Recursion class Program static void Main(string[] args) int n i = 0 c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First 5 terms of Fibonacci series are) for (c = 1 c lt= n c++) ConsoleWriteLine(Fibonacci(i)) i++ ConsoleReadKey() static int Fibonacci(int n) if (n == 0) return 0 else if (n == 1) return 1 else return (Fibonacci(n - 1) + Fibonacci(n - 2))

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 26

Get Date Difference in C

Getting differences in two given dates is as easy as it gets The function used here is the

End_DateSubtract(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

using System using SystemText namespace Print_and_Get_Date_Difference_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) ConsoleWriteLine(The Date Today Is) DateTime DT = new DateTime() DT = DateTimeTodayDate ConsoleWriteLine(DTDateToString()) ConsoleWriteLine(Calculate the difference between two datesn) int year month day ConsoleWriteLine(Enter Start Date) ConsoleWriteLine(Enter Year)

httpwwwcode-kingsblogspotcom Page 27

year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_Start = new DateTime(yearmonthday) ConsoleWriteLine(nEnter End Date) ConsoleWriteLine(Enter Year) year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_End = new DateTime(year month day) TimeSpan timespan = DT_EndSubtract(DT_Start) ConsoleWriteLine(nThe Difference isn) ConsoleWriteLine(timespanTotalDaysToString() + Daysn) ConsoleWriteLine((timespanTotalDays 365)ToString() + Years) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 28

Obtain Local Host IP in C

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 SystemNet

namespace Obtain_IP_Address_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) String StringHost if (argsLength == 0) Getting Ip address of local machine First get the host name of local machine StringHost = SystemNetDnsGetHostName() ConsoleWriteLine(Local Machine Host Name is + StringHost) ConsoleWriteLine() else StringHost = args[0]

httpwwwcode-kingsblogspotcom Page 29

Then using host name get the IP address list IPHostEntry ipEntry = SystemNetDnsGetHostEntry(StringHost) IPAddress[] address = ipEntryAddressList for (int i = 0 i lt addressLength i++) ConsoleWriteLine() ConsoleWriteLine(IP Address Type 0 1 i address[i]ToString()) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 30

Monitor Turn OnOffStandBy in C

You might want to change your display settings in a running program The code behind requires

the Import of a Dll amp execution of a function SendMessage() by supplying 4 parameters The

value of the fourth parameter having values 0 1 amp 2 has the monitor in the states ON STAND

BY amp 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 SystemWindowsForms using SystemRuntimeInteropServices namespace Turn_Off_Monitor public partial class Form1 Form public Form1() InitializeComponent() [DllImport(user32dll)] public static extern IntPtr SendMessage(IntPtr hWnd uint 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(thisHandle WM_SYSCOMMAND b a) private void btnMonitorOff_Click(object sender EventArgs e) IntPtr a = new IntPtr(2) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

httpwwwcode-kingsblogspotcom Page 31

private void btnMonitorOn_Click(object sender EventArgs e) IntPtr a = new IntPtr(-1) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 32

Search Techniques Linear amp Binary

Searching is needed when we have a large array of some data or objects amp 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 amp finds the

position of elements Below you will find two search techniques viz Linear Search amp Binary

Search implemented in C The code is simple amp easy to understand amp can be modified as per

need

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 33

Code for Linear Search Technique in C Sharp

using System

using SystemText

using SystemThreadingTasks

namespace Linear_Search

class Program

static void Main(string[] args)

Int16[] array = new Int16[100]

Int16 search c number

ConsoleWriteLine(Enter the number of elements in arrayn)

number = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + numberToString() + numbersn)

for (c = 0 c lt number c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter the number to searchn)

search = ConvertToInt16(ConsoleReadLine())

for (c = 0 c lt number c++)

if (array[c] == search) if required element found

ConsoleWriteLine(searchToString() + is at locn + (c + 1)ToString() + n)

break

if (c == number)

ConsoleWriteLine(searchToString() + is not present in arrayn)

ConsoleReadLine()

httpwwwcode-kingsblogspotcom Page 34

Code for Binary Search Technique in C Sharp

namespace Binary_Search

class Program

static void Main(string[] args)

int c first last middle n search

Int16[] array = new Int16[100]

ConsoleWriteLine(Enter number of elementsn)

n = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + nToString() + integersn)

for (c = 0 c lt n c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter value to findn)

search = ConvertToInt16(ConsoleReadLine())

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

while (first lt= last)

if (array[middle] lt search)

first = middle + 1

else if (array[middle] == search)

ConsoleWriteLine(search + found at location + (middle + 1))

break

else

last = middle - 1

middle = (first + last) 2

if (first gt last)

ConsoleWriteLine(Not found + search + is not present in the list)

httpwwwcode-kingsblogspotcom Page 35

Working With Strings The 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 amp 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 txtLengthText = textBoxTextLengthToString() trkBar1Maximum = textBoxTextLength private void trackBar1_Scroll(object sender EventArgs e) Set the Max Value of second TrackBar trkBar2Maximum = textBoxTextLength - trkBar1Value textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString()

httpwwwcode-kingsblogspotcom Page 36

txtTotCharsText = trkBar2ValueToString() textBoxSelect()

Let us understand the working of this property with a simple String ABCDEFGH Suppose

you wanted to select the characters from between B amp C and Between F amp 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 ie

include A as well in the selection

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 ie a reduced

Maximum value

private void trackBar2_Scroll(object sender EventArgs e) textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString() txtTotCharsText = trkBar2ValueToString()

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 5: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 5

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) txtAdditionText = txtXText + + + txtYText + = +

ConvertToString(ConvertToInt32((ConvertToInt32(txtXText))+(ConvertToInt3

2(txtYText))))

private void Subtraction_Click(object sender EventArgs e) txtSubtractionText = txtXText + - + txtYText + = +

ConvertToString(ConvertToInt32((ConvertToInt32(txtXText)) -

(ConvertToInt32(txtYText))))

private void Multiplication_Click(object sender EventArgs e) txtMultiplicationText = txtXText + + txtYText + = +

ConvertToString(ConvertToInt32((ConvertToInt32(txtXText))

(ConvertToInt32(txtYText))))

private void Division_Click(object sender EventArgs e) txtDivisionText = txtXText + + txtYText + = +

ConvertToString(ConvertToInt32((ConvertToInt32(txtXText))

(ConvertToInt32(txtYText))))

private void SinX_Click(object sender EventArgs e) txtSinXText = Sin +txtXText + = +

ConvertToString(MathSin(ConvertToDouble(txtXText))) private void CosX_Click(object sender EventArgs e) txtCosXText = Cos + txtXText + = +

ConvertToString(MathCos(ConvertToDouble(txtXText)))

httpwwwcode-kingsblogspotcom Page 6

private void TanX_Click(object sender EventArgs e) txtTanXText = Tan + txtXText + = +

ConvertToString(MathTan(ConvertToDouble(txtXText)))

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 7

Create Controls at Runtime in C 5

Sometimes you might want to create a user control at runtime There are times when you are not

sure of what controls to include during the designing phase of your forms In these cases what

usally is done is that we draw all available controls in the designer and at runtime we simply

make the controls invisible during runtime leaving us with workable visible controls But this is

not the right method What should be done is exactly illustrated below You should draw the

controls at runtime Yes you should draw the controls only 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 method to create them If you look carefully in the

Designer of any form you will find codes that initiate the creation of controls You will see some

properties set leaving other properties default And this is exactly what we are doing here We

are writing code behinf the Fom that creates the controls with some properties set by ourselves amp

others are simply set to their default value by the Compiler

The main steps to draw controls are summarized below

CreateDefine the control or Array of controls

Set the properties of the control or individual controls in case of Arrays

Add the controls to the form or other parent containers such as Panels

Call the Show() method to display the control

Thats it

httpwwwcode-kingsblogspotcom Page 8

The code below shows how to draw controls

namespace CreateControlsAtRuntime 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 lt= 6 i++) tb[i] = new TextBox() tb[i]Width = 150 tb[i]Left = 20 tb[i]Top = (30 i) + 30 tb[i]Text = Text Box Number + iToString() thisControlsAdd(tb[i]) tb[i]Show()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 9

Check for Anagrams in Net C

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 for 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 lt aLength c++) first[a[c] - a]++ c = 0 for (c=0 cltbLength c++) second[b[c] - a]++ for (c = 0 c lt 26 c++) if (first[c] = second[c]) return 0 return 1

httpwwwcode-kingsblogspotcom Page 10

using System namespace Anagram_Test class Program static void Main(string[] args) ClassCheckAnagram cca = new ClassCheckAnagram() ConsoleWriteLine(Enter first stringn) string aa = ConsoleReadLine() char[] a = aaToCharArray() ConsoleWriteLine(nEnter second stringn) string bb = ConsoleReadLine() char[] b = bbToCharArray() int flag = ccacheck_anagram(a b) if (flag == 1) ConsoleWriteLine(nThey are anagramsn) else ConsoleWriteLine(nThey are not anagramsn) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 11

Using Indexers in C 5

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

obj1RollNumberVariable[0] obj1RollNumberVariable[1]

where RollNumberVariable would be the Integer variable

Now that you have learnt how to index your class amp 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 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 lt size i++) RollNumberVariable[i] = 0

httpwwwcode-kingsblogspotcom Page 12

public Int16 this[int pos] get return RollNumberVariable[pos] set RollNumberVariable[pos] = value using System namespace Indexers_Example class Program static void Main(string[] args) Int16 size = 5 Indexers obj1 = new Indexers(size) for (int i = 0 i lt size i++) obj1[i] = (short)i ConsoleWriteLine(nIndexer Outputn) for (int i = 0 i lt size i++) ConsoleWriteLine(Next Roll No + obj1[i]) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 13

How to Write into Windows Registry in C

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 as shown below

The Keys at the parent level are HKEY_CLASSES_ROOT HKEY_CURRENT_USER etc When we refer to

these keys in our C program code we omit the HKEY amp the underscores So to refer to the

HKEY_CURRENT_USER we use simply CurrentUser as the reference Well this reference is available

from the MicrosoftWin32Registry class This Registry class is available through the reference

using MicrosoftWin32

We use this reference to create a Key object An example of a Key object would be

MicrosoftWin32RegistryKey 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 = MicrosoftWin32RegistryClassesRootCreateSubKey(CSharp_Website)

Next we can set the Value of this Field using the SetValue() funtion See below

keySetValue(Really Yes)

httpwwwcode-kingsblogspotcom Page 14

The output shown below

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 15

Convert From Decimal to Binary System

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 gtgt

using System

namespace convert_decimal_to_binary

class Program

static void Main(string[] args)

int n c k

ConsoleWriteLine(Enter an integer in Decimal number systemn)

n = ConvertToInt32(ConsoleReadLine())

ConsoleWriteLine(nBinary Equivalent isn)

for (c = 31 c gt= 0 c--)

k = n gtgt c

if (ConvertToBoolean(k amp 1))

ConsoleWrite(1)

else

ConsoleWrite(0)

ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 16

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 TraceWriteLine() 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)

TraceWriteLine(message + message)

TraceWriteLine(member name + memberName)

TraceWriteLine(source file path + sourceFilePath)

TraceWriteLine(source line number + sourceLineNumber)

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

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 17

Reverse the Words in a Given 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 = strSourceSplit(new char[] ) string strReverse = stringEmpty for (int i = arySourceLength - 1 i gt= 0 i--) strReverse = strReverse + + arySource[i] ConsoleWriteLine(Original String nn + strSource) ConsoleWriteLine(nnReversed String nn + strReverse) return strReverse

httpwwwcode-kingsblogspotcom Page 18

static void Main(string[] args) reverseIt( I Am In Love With wwwcode-kingsblogspotcomcom) ConsoleWriteLine(nPress any key to continue) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 19

Named ArgumentsParameters in C

Named Arguments are an alternative way for specifing 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 specifiying 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

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 divisor5)

int a = remainder(divisor5 dividend 10)

Note that the position of the arguments have been interchanged both the above methods will

produce the same output ie they would set the value of a as 0(which is the remainder when

dividing 10 by 5)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 20

Optional ArgumentsParameters in C

This article will show you what is meant by Optional ArgumentsParameters in C 50 Optional

Arguments are mostly necessary when you specify functions that have a large number of

arguments

Optional Arguments are purely optional ie even if you do not specify them its perfectly OK

But it doesnt 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

The values that we supply in the function Definition are some constants These are the values

that are to be used in case no value is supplied in the function call These values are specified by

typing in variable expressions instead of just the declaration of variables

For example we would write

static void Func(Str = Default Value)

instead of static void Func(int Str)

If you didnt 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

When using this technique it is best that you have declared optional amp required parameters both

ie 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 = NA)

In the example above Name amp Age are required parameters The string Address is optional if

not specified then it would take the value NA meaning that 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)

Please Note

Do not Copy amp Paste code written here instead type it in your Development

Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 21

Transpose a Matrix

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

details

using System using SystemText using SystemThreadingTasks 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] ConsoleWriteLine(Enter the number of rows and columns of matrix ) m = ConvertToInt16(ConsoleReadLine()) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(Enter the elements of matrix n) for (c = 0 c lt m c++) for (d = 0 d lt n d++) matrix[c d] = ConvertToInt16(ConsoleReadLine()) for (c = 0 c lt m c++) for (d = 0 d lt n d++) transpose[d c] = matrix[c d]

httpwwwcode-kingsblogspotcom Page 22

ConsoleWriteLine(Transpose of entered matrix) for (c = 0 c lt n c++) for (d = 0 d lt m d++) ConsoleWrite( + transpose[c d]) ConsoleWriteLine() ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 23

Fibonacci Series

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 amp 1 The series goes on like

this

01123581321345589144233377helliphellip

Here we illustrate two techniques for the creation of the Fibonacci Series to n terms The For

Loop method amp 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 amp Second) Then we calculate the next term by adding these two terms amp setting a

new set of two new terms These terms are the Second amp Newest

using System using SystemText using SystemThreadingTasks namespace Fibonacci_series_Using_For_Loop class Program static void Main(string[] args) int n first = 0 second = 1 next c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First + n + terms of Fibonacci series are) for (c = 0 c lt n c++) if (c lt= 1) next = c

httpwwwcode-kingsblogspotcom Page 24

else next = first + second first = second second = next ConsoleWriteLine(next) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 25

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 amp two less than the number supplied In this way final

output value has each number added twice excluding 0 amp 1 Check the program below

using System using SystemText using SystemThreadingTasks namespace Fibonacci_Series_Recursion class Program static void Main(string[] args) int n i = 0 c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First 5 terms of Fibonacci series are) for (c = 1 c lt= n c++) ConsoleWriteLine(Fibonacci(i)) i++ ConsoleReadKey() static int Fibonacci(int n) if (n == 0) return 0 else if (n == 1) return 1 else return (Fibonacci(n - 1) + Fibonacci(n - 2))

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 26

Get Date Difference in C

Getting differences in two given dates is as easy as it gets The function used here is the

End_DateSubtract(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

using System using SystemText namespace Print_and_Get_Date_Difference_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) ConsoleWriteLine(The Date Today Is) DateTime DT = new DateTime() DT = DateTimeTodayDate ConsoleWriteLine(DTDateToString()) ConsoleWriteLine(Calculate the difference between two datesn) int year month day ConsoleWriteLine(Enter Start Date) ConsoleWriteLine(Enter Year)

httpwwwcode-kingsblogspotcom Page 27

year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_Start = new DateTime(yearmonthday) ConsoleWriteLine(nEnter End Date) ConsoleWriteLine(Enter Year) year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_End = new DateTime(year month day) TimeSpan timespan = DT_EndSubtract(DT_Start) ConsoleWriteLine(nThe Difference isn) ConsoleWriteLine(timespanTotalDaysToString() + Daysn) ConsoleWriteLine((timespanTotalDays 365)ToString() + Years) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 28

Obtain Local Host IP in C

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 SystemNet

namespace Obtain_IP_Address_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) String StringHost if (argsLength == 0) Getting Ip address of local machine First get the host name of local machine StringHost = SystemNetDnsGetHostName() ConsoleWriteLine(Local Machine Host Name is + StringHost) ConsoleWriteLine() else StringHost = args[0]

httpwwwcode-kingsblogspotcom Page 29

Then using host name get the IP address list IPHostEntry ipEntry = SystemNetDnsGetHostEntry(StringHost) IPAddress[] address = ipEntryAddressList for (int i = 0 i lt addressLength i++) ConsoleWriteLine() ConsoleWriteLine(IP Address Type 0 1 i address[i]ToString()) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 30

Monitor Turn OnOffStandBy in C

You might want to change your display settings in a running program The code behind requires

the Import of a Dll amp execution of a function SendMessage() by supplying 4 parameters The

value of the fourth parameter having values 0 1 amp 2 has the monitor in the states ON STAND

BY amp 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 SystemWindowsForms using SystemRuntimeInteropServices namespace Turn_Off_Monitor public partial class Form1 Form public Form1() InitializeComponent() [DllImport(user32dll)] public static extern IntPtr SendMessage(IntPtr hWnd uint 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(thisHandle WM_SYSCOMMAND b a) private void btnMonitorOff_Click(object sender EventArgs e) IntPtr a = new IntPtr(2) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

httpwwwcode-kingsblogspotcom Page 31

private void btnMonitorOn_Click(object sender EventArgs e) IntPtr a = new IntPtr(-1) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 32

Search Techniques Linear amp Binary

Searching is needed when we have a large array of some data or objects amp 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 amp finds the

position of elements Below you will find two search techniques viz Linear Search amp Binary

Search implemented in C The code is simple amp easy to understand amp can be modified as per

need

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 33

Code for Linear Search Technique in C Sharp

using System

using SystemText

using SystemThreadingTasks

namespace Linear_Search

class Program

static void Main(string[] args)

Int16[] array = new Int16[100]

Int16 search c number

ConsoleWriteLine(Enter the number of elements in arrayn)

number = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + numberToString() + numbersn)

for (c = 0 c lt number c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter the number to searchn)

search = ConvertToInt16(ConsoleReadLine())

for (c = 0 c lt number c++)

if (array[c] == search) if required element found

ConsoleWriteLine(searchToString() + is at locn + (c + 1)ToString() + n)

break

if (c == number)

ConsoleWriteLine(searchToString() + is not present in arrayn)

ConsoleReadLine()

httpwwwcode-kingsblogspotcom Page 34

Code for Binary Search Technique in C Sharp

namespace Binary_Search

class Program

static void Main(string[] args)

int c first last middle n search

Int16[] array = new Int16[100]

ConsoleWriteLine(Enter number of elementsn)

n = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + nToString() + integersn)

for (c = 0 c lt n c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter value to findn)

search = ConvertToInt16(ConsoleReadLine())

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

while (first lt= last)

if (array[middle] lt search)

first = middle + 1

else if (array[middle] == search)

ConsoleWriteLine(search + found at location + (middle + 1))

break

else

last = middle - 1

middle = (first + last) 2

if (first gt last)

ConsoleWriteLine(Not found + search + is not present in the list)

httpwwwcode-kingsblogspotcom Page 35

Working With Strings The 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 amp 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 txtLengthText = textBoxTextLengthToString() trkBar1Maximum = textBoxTextLength private void trackBar1_Scroll(object sender EventArgs e) Set the Max Value of second TrackBar trkBar2Maximum = textBoxTextLength - trkBar1Value textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString()

httpwwwcode-kingsblogspotcom Page 36

txtTotCharsText = trkBar2ValueToString() textBoxSelect()

Let us understand the working of this property with a simple String ABCDEFGH Suppose

you wanted to select the characters from between B amp C and Between F amp 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 ie

include A as well in the selection

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 ie a reduced

Maximum value

private void trackBar2_Scroll(object sender EventArgs e) textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString() txtTotCharsText = trkBar2ValueToString()

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 6: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 6

private void TanX_Click(object sender EventArgs e) txtTanXText = Tan + txtXText + = +

ConvertToString(MathTan(ConvertToDouble(txtXText)))

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 7

Create Controls at Runtime in C 5

Sometimes you might want to create a user control at runtime There are times when you are not

sure of what controls to include during the designing phase of your forms In these cases what

usally is done is that we draw all available controls in the designer and at runtime we simply

make the controls invisible during runtime leaving us with workable visible controls But this is

not the right method What should be done is exactly illustrated below You should draw the

controls at runtime Yes you should draw the controls only 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 method to create them If you look carefully in the

Designer of any form you will find codes that initiate the creation of controls You will see some

properties set leaving other properties default And this is exactly what we are doing here We

are writing code behinf the Fom that creates the controls with some properties set by ourselves amp

others are simply set to their default value by the Compiler

The main steps to draw controls are summarized below

CreateDefine the control or Array of controls

Set the properties of the control or individual controls in case of Arrays

Add the controls to the form or other parent containers such as Panels

Call the Show() method to display the control

Thats it

httpwwwcode-kingsblogspotcom Page 8

The code below shows how to draw controls

namespace CreateControlsAtRuntime 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 lt= 6 i++) tb[i] = new TextBox() tb[i]Width = 150 tb[i]Left = 20 tb[i]Top = (30 i) + 30 tb[i]Text = Text Box Number + iToString() thisControlsAdd(tb[i]) tb[i]Show()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 9

Check for Anagrams in Net C

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 for 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 lt aLength c++) first[a[c] - a]++ c = 0 for (c=0 cltbLength c++) second[b[c] - a]++ for (c = 0 c lt 26 c++) if (first[c] = second[c]) return 0 return 1

httpwwwcode-kingsblogspotcom Page 10

using System namespace Anagram_Test class Program static void Main(string[] args) ClassCheckAnagram cca = new ClassCheckAnagram() ConsoleWriteLine(Enter first stringn) string aa = ConsoleReadLine() char[] a = aaToCharArray() ConsoleWriteLine(nEnter second stringn) string bb = ConsoleReadLine() char[] b = bbToCharArray() int flag = ccacheck_anagram(a b) if (flag == 1) ConsoleWriteLine(nThey are anagramsn) else ConsoleWriteLine(nThey are not anagramsn) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 11

Using Indexers in C 5

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

obj1RollNumberVariable[0] obj1RollNumberVariable[1]

where RollNumberVariable would be the Integer variable

Now that you have learnt how to index your class amp 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 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 lt size i++) RollNumberVariable[i] = 0

httpwwwcode-kingsblogspotcom Page 12

public Int16 this[int pos] get return RollNumberVariable[pos] set RollNumberVariable[pos] = value using System namespace Indexers_Example class Program static void Main(string[] args) Int16 size = 5 Indexers obj1 = new Indexers(size) for (int i = 0 i lt size i++) obj1[i] = (short)i ConsoleWriteLine(nIndexer Outputn) for (int i = 0 i lt size i++) ConsoleWriteLine(Next Roll No + obj1[i]) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 13

How to Write into Windows Registry in C

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 as shown below

The Keys at the parent level are HKEY_CLASSES_ROOT HKEY_CURRENT_USER etc When we refer to

these keys in our C program code we omit the HKEY amp the underscores So to refer to the

HKEY_CURRENT_USER we use simply CurrentUser as the reference Well this reference is available

from the MicrosoftWin32Registry class This Registry class is available through the reference

using MicrosoftWin32

We use this reference to create a Key object An example of a Key object would be

MicrosoftWin32RegistryKey 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 = MicrosoftWin32RegistryClassesRootCreateSubKey(CSharp_Website)

Next we can set the Value of this Field using the SetValue() funtion See below

keySetValue(Really Yes)

httpwwwcode-kingsblogspotcom Page 14

The output shown below

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 15

Convert From Decimal to Binary System

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 gtgt

using System

namespace convert_decimal_to_binary

class Program

static void Main(string[] args)

int n c k

ConsoleWriteLine(Enter an integer in Decimal number systemn)

n = ConvertToInt32(ConsoleReadLine())

ConsoleWriteLine(nBinary Equivalent isn)

for (c = 31 c gt= 0 c--)

k = n gtgt c

if (ConvertToBoolean(k amp 1))

ConsoleWrite(1)

else

ConsoleWrite(0)

ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 16

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 TraceWriteLine() 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)

TraceWriteLine(message + message)

TraceWriteLine(member name + memberName)

TraceWriteLine(source file path + sourceFilePath)

TraceWriteLine(source line number + sourceLineNumber)

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

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 17

Reverse the Words in a Given 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 = strSourceSplit(new char[] ) string strReverse = stringEmpty for (int i = arySourceLength - 1 i gt= 0 i--) strReverse = strReverse + + arySource[i] ConsoleWriteLine(Original String nn + strSource) ConsoleWriteLine(nnReversed String nn + strReverse) return strReverse

httpwwwcode-kingsblogspotcom Page 18

static void Main(string[] args) reverseIt( I Am In Love With wwwcode-kingsblogspotcomcom) ConsoleWriteLine(nPress any key to continue) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 19

Named ArgumentsParameters in C

Named Arguments are an alternative way for specifing 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 specifiying 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

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 divisor5)

int a = remainder(divisor5 dividend 10)

Note that the position of the arguments have been interchanged both the above methods will

produce the same output ie they would set the value of a as 0(which is the remainder when

dividing 10 by 5)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 20

Optional ArgumentsParameters in C

This article will show you what is meant by Optional ArgumentsParameters in C 50 Optional

Arguments are mostly necessary when you specify functions that have a large number of

arguments

Optional Arguments are purely optional ie even if you do not specify them its perfectly OK

But it doesnt 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

The values that we supply in the function Definition are some constants These are the values

that are to be used in case no value is supplied in the function call These values are specified by

typing in variable expressions instead of just the declaration of variables

For example we would write

static void Func(Str = Default Value)

instead of static void Func(int Str)

If you didnt 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

When using this technique it is best that you have declared optional amp required parameters both

ie 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 = NA)

In the example above Name amp Age are required parameters The string Address is optional if

not specified then it would take the value NA meaning that 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)

Please Note

Do not Copy amp Paste code written here instead type it in your Development

Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 21

Transpose a Matrix

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

details

using System using SystemText using SystemThreadingTasks 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] ConsoleWriteLine(Enter the number of rows and columns of matrix ) m = ConvertToInt16(ConsoleReadLine()) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(Enter the elements of matrix n) for (c = 0 c lt m c++) for (d = 0 d lt n d++) matrix[c d] = ConvertToInt16(ConsoleReadLine()) for (c = 0 c lt m c++) for (d = 0 d lt n d++) transpose[d c] = matrix[c d]

httpwwwcode-kingsblogspotcom Page 22

ConsoleWriteLine(Transpose of entered matrix) for (c = 0 c lt n c++) for (d = 0 d lt m d++) ConsoleWrite( + transpose[c d]) ConsoleWriteLine() ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 23

Fibonacci Series

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 amp 1 The series goes on like

this

01123581321345589144233377helliphellip

Here we illustrate two techniques for the creation of the Fibonacci Series to n terms The For

Loop method amp 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 amp Second) Then we calculate the next term by adding these two terms amp setting a

new set of two new terms These terms are the Second amp Newest

using System using SystemText using SystemThreadingTasks namespace Fibonacci_series_Using_For_Loop class Program static void Main(string[] args) int n first = 0 second = 1 next c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First + n + terms of Fibonacci series are) for (c = 0 c lt n c++) if (c lt= 1) next = c

httpwwwcode-kingsblogspotcom Page 24

else next = first + second first = second second = next ConsoleWriteLine(next) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 25

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 amp two less than the number supplied In this way final

output value has each number added twice excluding 0 amp 1 Check the program below

using System using SystemText using SystemThreadingTasks namespace Fibonacci_Series_Recursion class Program static void Main(string[] args) int n i = 0 c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First 5 terms of Fibonacci series are) for (c = 1 c lt= n c++) ConsoleWriteLine(Fibonacci(i)) i++ ConsoleReadKey() static int Fibonacci(int n) if (n == 0) return 0 else if (n == 1) return 1 else return (Fibonacci(n - 1) + Fibonacci(n - 2))

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 26

Get Date Difference in C

Getting differences in two given dates is as easy as it gets The function used here is the

End_DateSubtract(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

using System using SystemText namespace Print_and_Get_Date_Difference_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) ConsoleWriteLine(The Date Today Is) DateTime DT = new DateTime() DT = DateTimeTodayDate ConsoleWriteLine(DTDateToString()) ConsoleWriteLine(Calculate the difference between two datesn) int year month day ConsoleWriteLine(Enter Start Date) ConsoleWriteLine(Enter Year)

httpwwwcode-kingsblogspotcom Page 27

year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_Start = new DateTime(yearmonthday) ConsoleWriteLine(nEnter End Date) ConsoleWriteLine(Enter Year) year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_End = new DateTime(year month day) TimeSpan timespan = DT_EndSubtract(DT_Start) ConsoleWriteLine(nThe Difference isn) ConsoleWriteLine(timespanTotalDaysToString() + Daysn) ConsoleWriteLine((timespanTotalDays 365)ToString() + Years) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 28

Obtain Local Host IP in C

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 SystemNet

namespace Obtain_IP_Address_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) String StringHost if (argsLength == 0) Getting Ip address of local machine First get the host name of local machine StringHost = SystemNetDnsGetHostName() ConsoleWriteLine(Local Machine Host Name is + StringHost) ConsoleWriteLine() else StringHost = args[0]

httpwwwcode-kingsblogspotcom Page 29

Then using host name get the IP address list IPHostEntry ipEntry = SystemNetDnsGetHostEntry(StringHost) IPAddress[] address = ipEntryAddressList for (int i = 0 i lt addressLength i++) ConsoleWriteLine() ConsoleWriteLine(IP Address Type 0 1 i address[i]ToString()) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 30

Monitor Turn OnOffStandBy in C

You might want to change your display settings in a running program The code behind requires

the Import of a Dll amp execution of a function SendMessage() by supplying 4 parameters The

value of the fourth parameter having values 0 1 amp 2 has the monitor in the states ON STAND

BY amp 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 SystemWindowsForms using SystemRuntimeInteropServices namespace Turn_Off_Monitor public partial class Form1 Form public Form1() InitializeComponent() [DllImport(user32dll)] public static extern IntPtr SendMessage(IntPtr hWnd uint 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(thisHandle WM_SYSCOMMAND b a) private void btnMonitorOff_Click(object sender EventArgs e) IntPtr a = new IntPtr(2) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

httpwwwcode-kingsblogspotcom Page 31

private void btnMonitorOn_Click(object sender EventArgs e) IntPtr a = new IntPtr(-1) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 32

Search Techniques Linear amp Binary

Searching is needed when we have a large array of some data or objects amp 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 amp finds the

position of elements Below you will find two search techniques viz Linear Search amp Binary

Search implemented in C The code is simple amp easy to understand amp can be modified as per

need

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 33

Code for Linear Search Technique in C Sharp

using System

using SystemText

using SystemThreadingTasks

namespace Linear_Search

class Program

static void Main(string[] args)

Int16[] array = new Int16[100]

Int16 search c number

ConsoleWriteLine(Enter the number of elements in arrayn)

number = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + numberToString() + numbersn)

for (c = 0 c lt number c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter the number to searchn)

search = ConvertToInt16(ConsoleReadLine())

for (c = 0 c lt number c++)

if (array[c] == search) if required element found

ConsoleWriteLine(searchToString() + is at locn + (c + 1)ToString() + n)

break

if (c == number)

ConsoleWriteLine(searchToString() + is not present in arrayn)

ConsoleReadLine()

httpwwwcode-kingsblogspotcom Page 34

Code for Binary Search Technique in C Sharp

namespace Binary_Search

class Program

static void Main(string[] args)

int c first last middle n search

Int16[] array = new Int16[100]

ConsoleWriteLine(Enter number of elementsn)

n = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + nToString() + integersn)

for (c = 0 c lt n c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter value to findn)

search = ConvertToInt16(ConsoleReadLine())

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

while (first lt= last)

if (array[middle] lt search)

first = middle + 1

else if (array[middle] == search)

ConsoleWriteLine(search + found at location + (middle + 1))

break

else

last = middle - 1

middle = (first + last) 2

if (first gt last)

ConsoleWriteLine(Not found + search + is not present in the list)

httpwwwcode-kingsblogspotcom Page 35

Working With Strings The 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 amp 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 txtLengthText = textBoxTextLengthToString() trkBar1Maximum = textBoxTextLength private void trackBar1_Scroll(object sender EventArgs e) Set the Max Value of second TrackBar trkBar2Maximum = textBoxTextLength - trkBar1Value textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString()

httpwwwcode-kingsblogspotcom Page 36

txtTotCharsText = trkBar2ValueToString() textBoxSelect()

Let us understand the working of this property with a simple String ABCDEFGH Suppose

you wanted to select the characters from between B amp C and Between F amp 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 ie

include A as well in the selection

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 ie a reduced

Maximum value

private void trackBar2_Scroll(object sender EventArgs e) textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString() txtTotCharsText = trkBar2ValueToString()

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 7: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 7

Create Controls at Runtime in C 5

Sometimes you might want to create a user control at runtime There are times when you are not

sure of what controls to include during the designing phase of your forms In these cases what

usally is done is that we draw all available controls in the designer and at runtime we simply

make the controls invisible during runtime leaving us with workable visible controls But this is

not the right method What should be done is exactly illustrated below You should draw the

controls at runtime Yes you should draw the controls only 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 method to create them If you look carefully in the

Designer of any form you will find codes that initiate the creation of controls You will see some

properties set leaving other properties default And this is exactly what we are doing here We

are writing code behinf the Fom that creates the controls with some properties set by ourselves amp

others are simply set to their default value by the Compiler

The main steps to draw controls are summarized below

CreateDefine the control or Array of controls

Set the properties of the control or individual controls in case of Arrays

Add the controls to the form or other parent containers such as Panels

Call the Show() method to display the control

Thats it

httpwwwcode-kingsblogspotcom Page 8

The code below shows how to draw controls

namespace CreateControlsAtRuntime 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 lt= 6 i++) tb[i] = new TextBox() tb[i]Width = 150 tb[i]Left = 20 tb[i]Top = (30 i) + 30 tb[i]Text = Text Box Number + iToString() thisControlsAdd(tb[i]) tb[i]Show()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 9

Check for Anagrams in Net C

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 for 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 lt aLength c++) first[a[c] - a]++ c = 0 for (c=0 cltbLength c++) second[b[c] - a]++ for (c = 0 c lt 26 c++) if (first[c] = second[c]) return 0 return 1

httpwwwcode-kingsblogspotcom Page 10

using System namespace Anagram_Test class Program static void Main(string[] args) ClassCheckAnagram cca = new ClassCheckAnagram() ConsoleWriteLine(Enter first stringn) string aa = ConsoleReadLine() char[] a = aaToCharArray() ConsoleWriteLine(nEnter second stringn) string bb = ConsoleReadLine() char[] b = bbToCharArray() int flag = ccacheck_anagram(a b) if (flag == 1) ConsoleWriteLine(nThey are anagramsn) else ConsoleWriteLine(nThey are not anagramsn) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 11

Using Indexers in C 5

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

obj1RollNumberVariable[0] obj1RollNumberVariable[1]

where RollNumberVariable would be the Integer variable

Now that you have learnt how to index your class amp 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 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 lt size i++) RollNumberVariable[i] = 0

httpwwwcode-kingsblogspotcom Page 12

public Int16 this[int pos] get return RollNumberVariable[pos] set RollNumberVariable[pos] = value using System namespace Indexers_Example class Program static void Main(string[] args) Int16 size = 5 Indexers obj1 = new Indexers(size) for (int i = 0 i lt size i++) obj1[i] = (short)i ConsoleWriteLine(nIndexer Outputn) for (int i = 0 i lt size i++) ConsoleWriteLine(Next Roll No + obj1[i]) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 13

How to Write into Windows Registry in C

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 as shown below

The Keys at the parent level are HKEY_CLASSES_ROOT HKEY_CURRENT_USER etc When we refer to

these keys in our C program code we omit the HKEY amp the underscores So to refer to the

HKEY_CURRENT_USER we use simply CurrentUser as the reference Well this reference is available

from the MicrosoftWin32Registry class This Registry class is available through the reference

using MicrosoftWin32

We use this reference to create a Key object An example of a Key object would be

MicrosoftWin32RegistryKey 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 = MicrosoftWin32RegistryClassesRootCreateSubKey(CSharp_Website)

Next we can set the Value of this Field using the SetValue() funtion See below

keySetValue(Really Yes)

httpwwwcode-kingsblogspotcom Page 14

The output shown below

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 15

Convert From Decimal to Binary System

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 gtgt

using System

namespace convert_decimal_to_binary

class Program

static void Main(string[] args)

int n c k

ConsoleWriteLine(Enter an integer in Decimal number systemn)

n = ConvertToInt32(ConsoleReadLine())

ConsoleWriteLine(nBinary Equivalent isn)

for (c = 31 c gt= 0 c--)

k = n gtgt c

if (ConvertToBoolean(k amp 1))

ConsoleWrite(1)

else

ConsoleWrite(0)

ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 16

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 TraceWriteLine() 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)

TraceWriteLine(message + message)

TraceWriteLine(member name + memberName)

TraceWriteLine(source file path + sourceFilePath)

TraceWriteLine(source line number + sourceLineNumber)

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

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 17

Reverse the Words in a Given 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 = strSourceSplit(new char[] ) string strReverse = stringEmpty for (int i = arySourceLength - 1 i gt= 0 i--) strReverse = strReverse + + arySource[i] ConsoleWriteLine(Original String nn + strSource) ConsoleWriteLine(nnReversed String nn + strReverse) return strReverse

httpwwwcode-kingsblogspotcom Page 18

static void Main(string[] args) reverseIt( I Am In Love With wwwcode-kingsblogspotcomcom) ConsoleWriteLine(nPress any key to continue) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 19

Named ArgumentsParameters in C

Named Arguments are an alternative way for specifing 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 specifiying 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

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 divisor5)

int a = remainder(divisor5 dividend 10)

Note that the position of the arguments have been interchanged both the above methods will

produce the same output ie they would set the value of a as 0(which is the remainder when

dividing 10 by 5)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 20

Optional ArgumentsParameters in C

This article will show you what is meant by Optional ArgumentsParameters in C 50 Optional

Arguments are mostly necessary when you specify functions that have a large number of

arguments

Optional Arguments are purely optional ie even if you do not specify them its perfectly OK

But it doesnt 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

The values that we supply in the function Definition are some constants These are the values

that are to be used in case no value is supplied in the function call These values are specified by

typing in variable expressions instead of just the declaration of variables

For example we would write

static void Func(Str = Default Value)

instead of static void Func(int Str)

If you didnt 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

When using this technique it is best that you have declared optional amp required parameters both

ie 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 = NA)

In the example above Name amp Age are required parameters The string Address is optional if

not specified then it would take the value NA meaning that 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)

Please Note

Do not Copy amp Paste code written here instead type it in your Development

Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 21

Transpose a Matrix

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

details

using System using SystemText using SystemThreadingTasks 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] ConsoleWriteLine(Enter the number of rows and columns of matrix ) m = ConvertToInt16(ConsoleReadLine()) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(Enter the elements of matrix n) for (c = 0 c lt m c++) for (d = 0 d lt n d++) matrix[c d] = ConvertToInt16(ConsoleReadLine()) for (c = 0 c lt m c++) for (d = 0 d lt n d++) transpose[d c] = matrix[c d]

httpwwwcode-kingsblogspotcom Page 22

ConsoleWriteLine(Transpose of entered matrix) for (c = 0 c lt n c++) for (d = 0 d lt m d++) ConsoleWrite( + transpose[c d]) ConsoleWriteLine() ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 23

Fibonacci Series

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 amp 1 The series goes on like

this

01123581321345589144233377helliphellip

Here we illustrate two techniques for the creation of the Fibonacci Series to n terms The For

Loop method amp 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 amp Second) Then we calculate the next term by adding these two terms amp setting a

new set of two new terms These terms are the Second amp Newest

using System using SystemText using SystemThreadingTasks namespace Fibonacci_series_Using_For_Loop class Program static void Main(string[] args) int n first = 0 second = 1 next c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First + n + terms of Fibonacci series are) for (c = 0 c lt n c++) if (c lt= 1) next = c

httpwwwcode-kingsblogspotcom Page 24

else next = first + second first = second second = next ConsoleWriteLine(next) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 25

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 amp two less than the number supplied In this way final

output value has each number added twice excluding 0 amp 1 Check the program below

using System using SystemText using SystemThreadingTasks namespace Fibonacci_Series_Recursion class Program static void Main(string[] args) int n i = 0 c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First 5 terms of Fibonacci series are) for (c = 1 c lt= n c++) ConsoleWriteLine(Fibonacci(i)) i++ ConsoleReadKey() static int Fibonacci(int n) if (n == 0) return 0 else if (n == 1) return 1 else return (Fibonacci(n - 1) + Fibonacci(n - 2))

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 26

Get Date Difference in C

Getting differences in two given dates is as easy as it gets The function used here is the

End_DateSubtract(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

using System using SystemText namespace Print_and_Get_Date_Difference_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) ConsoleWriteLine(The Date Today Is) DateTime DT = new DateTime() DT = DateTimeTodayDate ConsoleWriteLine(DTDateToString()) ConsoleWriteLine(Calculate the difference between two datesn) int year month day ConsoleWriteLine(Enter Start Date) ConsoleWriteLine(Enter Year)

httpwwwcode-kingsblogspotcom Page 27

year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_Start = new DateTime(yearmonthday) ConsoleWriteLine(nEnter End Date) ConsoleWriteLine(Enter Year) year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_End = new DateTime(year month day) TimeSpan timespan = DT_EndSubtract(DT_Start) ConsoleWriteLine(nThe Difference isn) ConsoleWriteLine(timespanTotalDaysToString() + Daysn) ConsoleWriteLine((timespanTotalDays 365)ToString() + Years) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 28

Obtain Local Host IP in C

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 SystemNet

namespace Obtain_IP_Address_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) String StringHost if (argsLength == 0) Getting Ip address of local machine First get the host name of local machine StringHost = SystemNetDnsGetHostName() ConsoleWriteLine(Local Machine Host Name is + StringHost) ConsoleWriteLine() else StringHost = args[0]

httpwwwcode-kingsblogspotcom Page 29

Then using host name get the IP address list IPHostEntry ipEntry = SystemNetDnsGetHostEntry(StringHost) IPAddress[] address = ipEntryAddressList for (int i = 0 i lt addressLength i++) ConsoleWriteLine() ConsoleWriteLine(IP Address Type 0 1 i address[i]ToString()) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 30

Monitor Turn OnOffStandBy in C

You might want to change your display settings in a running program The code behind requires

the Import of a Dll amp execution of a function SendMessage() by supplying 4 parameters The

value of the fourth parameter having values 0 1 amp 2 has the monitor in the states ON STAND

BY amp 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 SystemWindowsForms using SystemRuntimeInteropServices namespace Turn_Off_Monitor public partial class Form1 Form public Form1() InitializeComponent() [DllImport(user32dll)] public static extern IntPtr SendMessage(IntPtr hWnd uint 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(thisHandle WM_SYSCOMMAND b a) private void btnMonitorOff_Click(object sender EventArgs e) IntPtr a = new IntPtr(2) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

httpwwwcode-kingsblogspotcom Page 31

private void btnMonitorOn_Click(object sender EventArgs e) IntPtr a = new IntPtr(-1) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 32

Search Techniques Linear amp Binary

Searching is needed when we have a large array of some data or objects amp 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 amp finds the

position of elements Below you will find two search techniques viz Linear Search amp Binary

Search implemented in C The code is simple amp easy to understand amp can be modified as per

need

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 33

Code for Linear Search Technique in C Sharp

using System

using SystemText

using SystemThreadingTasks

namespace Linear_Search

class Program

static void Main(string[] args)

Int16[] array = new Int16[100]

Int16 search c number

ConsoleWriteLine(Enter the number of elements in arrayn)

number = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + numberToString() + numbersn)

for (c = 0 c lt number c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter the number to searchn)

search = ConvertToInt16(ConsoleReadLine())

for (c = 0 c lt number c++)

if (array[c] == search) if required element found

ConsoleWriteLine(searchToString() + is at locn + (c + 1)ToString() + n)

break

if (c == number)

ConsoleWriteLine(searchToString() + is not present in arrayn)

ConsoleReadLine()

httpwwwcode-kingsblogspotcom Page 34

Code for Binary Search Technique in C Sharp

namespace Binary_Search

class Program

static void Main(string[] args)

int c first last middle n search

Int16[] array = new Int16[100]

ConsoleWriteLine(Enter number of elementsn)

n = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + nToString() + integersn)

for (c = 0 c lt n c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter value to findn)

search = ConvertToInt16(ConsoleReadLine())

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

while (first lt= last)

if (array[middle] lt search)

first = middle + 1

else if (array[middle] == search)

ConsoleWriteLine(search + found at location + (middle + 1))

break

else

last = middle - 1

middle = (first + last) 2

if (first gt last)

ConsoleWriteLine(Not found + search + is not present in the list)

httpwwwcode-kingsblogspotcom Page 35

Working With Strings The 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 amp 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 txtLengthText = textBoxTextLengthToString() trkBar1Maximum = textBoxTextLength private void trackBar1_Scroll(object sender EventArgs e) Set the Max Value of second TrackBar trkBar2Maximum = textBoxTextLength - trkBar1Value textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString()

httpwwwcode-kingsblogspotcom Page 36

txtTotCharsText = trkBar2ValueToString() textBoxSelect()

Let us understand the working of this property with a simple String ABCDEFGH Suppose

you wanted to select the characters from between B amp C and Between F amp 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 ie

include A as well in the selection

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 ie a reduced

Maximum value

private void trackBar2_Scroll(object sender EventArgs e) textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString() txtTotCharsText = trkBar2ValueToString()

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 8: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 8

The code below shows how to draw controls

namespace CreateControlsAtRuntime 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 lt= 6 i++) tb[i] = new TextBox() tb[i]Width = 150 tb[i]Left = 20 tb[i]Top = (30 i) + 30 tb[i]Text = Text Box Number + iToString() thisControlsAdd(tb[i]) tb[i]Show()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 9

Check for Anagrams in Net C

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 for 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 lt aLength c++) first[a[c] - a]++ c = 0 for (c=0 cltbLength c++) second[b[c] - a]++ for (c = 0 c lt 26 c++) if (first[c] = second[c]) return 0 return 1

httpwwwcode-kingsblogspotcom Page 10

using System namespace Anagram_Test class Program static void Main(string[] args) ClassCheckAnagram cca = new ClassCheckAnagram() ConsoleWriteLine(Enter first stringn) string aa = ConsoleReadLine() char[] a = aaToCharArray() ConsoleWriteLine(nEnter second stringn) string bb = ConsoleReadLine() char[] b = bbToCharArray() int flag = ccacheck_anagram(a b) if (flag == 1) ConsoleWriteLine(nThey are anagramsn) else ConsoleWriteLine(nThey are not anagramsn) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 11

Using Indexers in C 5

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

obj1RollNumberVariable[0] obj1RollNumberVariable[1]

where RollNumberVariable would be the Integer variable

Now that you have learnt how to index your class amp 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 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 lt size i++) RollNumberVariable[i] = 0

httpwwwcode-kingsblogspotcom Page 12

public Int16 this[int pos] get return RollNumberVariable[pos] set RollNumberVariable[pos] = value using System namespace Indexers_Example class Program static void Main(string[] args) Int16 size = 5 Indexers obj1 = new Indexers(size) for (int i = 0 i lt size i++) obj1[i] = (short)i ConsoleWriteLine(nIndexer Outputn) for (int i = 0 i lt size i++) ConsoleWriteLine(Next Roll No + obj1[i]) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 13

How to Write into Windows Registry in C

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 as shown below

The Keys at the parent level are HKEY_CLASSES_ROOT HKEY_CURRENT_USER etc When we refer to

these keys in our C program code we omit the HKEY amp the underscores So to refer to the

HKEY_CURRENT_USER we use simply CurrentUser as the reference Well this reference is available

from the MicrosoftWin32Registry class This Registry class is available through the reference

using MicrosoftWin32

We use this reference to create a Key object An example of a Key object would be

MicrosoftWin32RegistryKey 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 = MicrosoftWin32RegistryClassesRootCreateSubKey(CSharp_Website)

Next we can set the Value of this Field using the SetValue() funtion See below

keySetValue(Really Yes)

httpwwwcode-kingsblogspotcom Page 14

The output shown below

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 15

Convert From Decimal to Binary System

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 gtgt

using System

namespace convert_decimal_to_binary

class Program

static void Main(string[] args)

int n c k

ConsoleWriteLine(Enter an integer in Decimal number systemn)

n = ConvertToInt32(ConsoleReadLine())

ConsoleWriteLine(nBinary Equivalent isn)

for (c = 31 c gt= 0 c--)

k = n gtgt c

if (ConvertToBoolean(k amp 1))

ConsoleWrite(1)

else

ConsoleWrite(0)

ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 16

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 TraceWriteLine() 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)

TraceWriteLine(message + message)

TraceWriteLine(member name + memberName)

TraceWriteLine(source file path + sourceFilePath)

TraceWriteLine(source line number + sourceLineNumber)

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

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 17

Reverse the Words in a Given 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 = strSourceSplit(new char[] ) string strReverse = stringEmpty for (int i = arySourceLength - 1 i gt= 0 i--) strReverse = strReverse + + arySource[i] ConsoleWriteLine(Original String nn + strSource) ConsoleWriteLine(nnReversed String nn + strReverse) return strReverse

httpwwwcode-kingsblogspotcom Page 18

static void Main(string[] args) reverseIt( I Am In Love With wwwcode-kingsblogspotcomcom) ConsoleWriteLine(nPress any key to continue) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 19

Named ArgumentsParameters in C

Named Arguments are an alternative way for specifing 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 specifiying 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

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 divisor5)

int a = remainder(divisor5 dividend 10)

Note that the position of the arguments have been interchanged both the above methods will

produce the same output ie they would set the value of a as 0(which is the remainder when

dividing 10 by 5)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 20

Optional ArgumentsParameters in C

This article will show you what is meant by Optional ArgumentsParameters in C 50 Optional

Arguments are mostly necessary when you specify functions that have a large number of

arguments

Optional Arguments are purely optional ie even if you do not specify them its perfectly OK

But it doesnt 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

The values that we supply in the function Definition are some constants These are the values

that are to be used in case no value is supplied in the function call These values are specified by

typing in variable expressions instead of just the declaration of variables

For example we would write

static void Func(Str = Default Value)

instead of static void Func(int Str)

If you didnt 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

When using this technique it is best that you have declared optional amp required parameters both

ie 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 = NA)

In the example above Name amp Age are required parameters The string Address is optional if

not specified then it would take the value NA meaning that 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)

Please Note

Do not Copy amp Paste code written here instead type it in your Development

Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 21

Transpose a Matrix

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

details

using System using SystemText using SystemThreadingTasks 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] ConsoleWriteLine(Enter the number of rows and columns of matrix ) m = ConvertToInt16(ConsoleReadLine()) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(Enter the elements of matrix n) for (c = 0 c lt m c++) for (d = 0 d lt n d++) matrix[c d] = ConvertToInt16(ConsoleReadLine()) for (c = 0 c lt m c++) for (d = 0 d lt n d++) transpose[d c] = matrix[c d]

httpwwwcode-kingsblogspotcom Page 22

ConsoleWriteLine(Transpose of entered matrix) for (c = 0 c lt n c++) for (d = 0 d lt m d++) ConsoleWrite( + transpose[c d]) ConsoleWriteLine() ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 23

Fibonacci Series

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 amp 1 The series goes on like

this

01123581321345589144233377helliphellip

Here we illustrate two techniques for the creation of the Fibonacci Series to n terms The For

Loop method amp 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 amp Second) Then we calculate the next term by adding these two terms amp setting a

new set of two new terms These terms are the Second amp Newest

using System using SystemText using SystemThreadingTasks namespace Fibonacci_series_Using_For_Loop class Program static void Main(string[] args) int n first = 0 second = 1 next c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First + n + terms of Fibonacci series are) for (c = 0 c lt n c++) if (c lt= 1) next = c

httpwwwcode-kingsblogspotcom Page 24

else next = first + second first = second second = next ConsoleWriteLine(next) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 25

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 amp two less than the number supplied In this way final

output value has each number added twice excluding 0 amp 1 Check the program below

using System using SystemText using SystemThreadingTasks namespace Fibonacci_Series_Recursion class Program static void Main(string[] args) int n i = 0 c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First 5 terms of Fibonacci series are) for (c = 1 c lt= n c++) ConsoleWriteLine(Fibonacci(i)) i++ ConsoleReadKey() static int Fibonacci(int n) if (n == 0) return 0 else if (n == 1) return 1 else return (Fibonacci(n - 1) + Fibonacci(n - 2))

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 26

Get Date Difference in C

Getting differences in two given dates is as easy as it gets The function used here is the

End_DateSubtract(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

using System using SystemText namespace Print_and_Get_Date_Difference_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) ConsoleWriteLine(The Date Today Is) DateTime DT = new DateTime() DT = DateTimeTodayDate ConsoleWriteLine(DTDateToString()) ConsoleWriteLine(Calculate the difference between two datesn) int year month day ConsoleWriteLine(Enter Start Date) ConsoleWriteLine(Enter Year)

httpwwwcode-kingsblogspotcom Page 27

year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_Start = new DateTime(yearmonthday) ConsoleWriteLine(nEnter End Date) ConsoleWriteLine(Enter Year) year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_End = new DateTime(year month day) TimeSpan timespan = DT_EndSubtract(DT_Start) ConsoleWriteLine(nThe Difference isn) ConsoleWriteLine(timespanTotalDaysToString() + Daysn) ConsoleWriteLine((timespanTotalDays 365)ToString() + Years) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 28

Obtain Local Host IP in C

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 SystemNet

namespace Obtain_IP_Address_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) String StringHost if (argsLength == 0) Getting Ip address of local machine First get the host name of local machine StringHost = SystemNetDnsGetHostName() ConsoleWriteLine(Local Machine Host Name is + StringHost) ConsoleWriteLine() else StringHost = args[0]

httpwwwcode-kingsblogspotcom Page 29

Then using host name get the IP address list IPHostEntry ipEntry = SystemNetDnsGetHostEntry(StringHost) IPAddress[] address = ipEntryAddressList for (int i = 0 i lt addressLength i++) ConsoleWriteLine() ConsoleWriteLine(IP Address Type 0 1 i address[i]ToString()) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 30

Monitor Turn OnOffStandBy in C

You might want to change your display settings in a running program The code behind requires

the Import of a Dll amp execution of a function SendMessage() by supplying 4 parameters The

value of the fourth parameter having values 0 1 amp 2 has the monitor in the states ON STAND

BY amp 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 SystemWindowsForms using SystemRuntimeInteropServices namespace Turn_Off_Monitor public partial class Form1 Form public Form1() InitializeComponent() [DllImport(user32dll)] public static extern IntPtr SendMessage(IntPtr hWnd uint 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(thisHandle WM_SYSCOMMAND b a) private void btnMonitorOff_Click(object sender EventArgs e) IntPtr a = new IntPtr(2) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

httpwwwcode-kingsblogspotcom Page 31

private void btnMonitorOn_Click(object sender EventArgs e) IntPtr a = new IntPtr(-1) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 32

Search Techniques Linear amp Binary

Searching is needed when we have a large array of some data or objects amp 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 amp finds the

position of elements Below you will find two search techniques viz Linear Search amp Binary

Search implemented in C The code is simple amp easy to understand amp can be modified as per

need

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 33

Code for Linear Search Technique in C Sharp

using System

using SystemText

using SystemThreadingTasks

namespace Linear_Search

class Program

static void Main(string[] args)

Int16[] array = new Int16[100]

Int16 search c number

ConsoleWriteLine(Enter the number of elements in arrayn)

number = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + numberToString() + numbersn)

for (c = 0 c lt number c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter the number to searchn)

search = ConvertToInt16(ConsoleReadLine())

for (c = 0 c lt number c++)

if (array[c] == search) if required element found

ConsoleWriteLine(searchToString() + is at locn + (c + 1)ToString() + n)

break

if (c == number)

ConsoleWriteLine(searchToString() + is not present in arrayn)

ConsoleReadLine()

httpwwwcode-kingsblogspotcom Page 34

Code for Binary Search Technique in C Sharp

namespace Binary_Search

class Program

static void Main(string[] args)

int c first last middle n search

Int16[] array = new Int16[100]

ConsoleWriteLine(Enter number of elementsn)

n = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + nToString() + integersn)

for (c = 0 c lt n c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter value to findn)

search = ConvertToInt16(ConsoleReadLine())

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

while (first lt= last)

if (array[middle] lt search)

first = middle + 1

else if (array[middle] == search)

ConsoleWriteLine(search + found at location + (middle + 1))

break

else

last = middle - 1

middle = (first + last) 2

if (first gt last)

ConsoleWriteLine(Not found + search + is not present in the list)

httpwwwcode-kingsblogspotcom Page 35

Working With Strings The 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 amp 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 txtLengthText = textBoxTextLengthToString() trkBar1Maximum = textBoxTextLength private void trackBar1_Scroll(object sender EventArgs e) Set the Max Value of second TrackBar trkBar2Maximum = textBoxTextLength - trkBar1Value textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString()

httpwwwcode-kingsblogspotcom Page 36

txtTotCharsText = trkBar2ValueToString() textBoxSelect()

Let us understand the working of this property with a simple String ABCDEFGH Suppose

you wanted to select the characters from between B amp C and Between F amp 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 ie

include A as well in the selection

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 ie a reduced

Maximum value

private void trackBar2_Scroll(object sender EventArgs e) textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString() txtTotCharsText = trkBar2ValueToString()

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 9: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 9

Check for Anagrams in Net C

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 for 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 lt aLength c++) first[a[c] - a]++ c = 0 for (c=0 cltbLength c++) second[b[c] - a]++ for (c = 0 c lt 26 c++) if (first[c] = second[c]) return 0 return 1

httpwwwcode-kingsblogspotcom Page 10

using System namespace Anagram_Test class Program static void Main(string[] args) ClassCheckAnagram cca = new ClassCheckAnagram() ConsoleWriteLine(Enter first stringn) string aa = ConsoleReadLine() char[] a = aaToCharArray() ConsoleWriteLine(nEnter second stringn) string bb = ConsoleReadLine() char[] b = bbToCharArray() int flag = ccacheck_anagram(a b) if (flag == 1) ConsoleWriteLine(nThey are anagramsn) else ConsoleWriteLine(nThey are not anagramsn) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 11

Using Indexers in C 5

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

obj1RollNumberVariable[0] obj1RollNumberVariable[1]

where RollNumberVariable would be the Integer variable

Now that you have learnt how to index your class amp 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 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 lt size i++) RollNumberVariable[i] = 0

httpwwwcode-kingsblogspotcom Page 12

public Int16 this[int pos] get return RollNumberVariable[pos] set RollNumberVariable[pos] = value using System namespace Indexers_Example class Program static void Main(string[] args) Int16 size = 5 Indexers obj1 = new Indexers(size) for (int i = 0 i lt size i++) obj1[i] = (short)i ConsoleWriteLine(nIndexer Outputn) for (int i = 0 i lt size i++) ConsoleWriteLine(Next Roll No + obj1[i]) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 13

How to Write into Windows Registry in C

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 as shown below

The Keys at the parent level are HKEY_CLASSES_ROOT HKEY_CURRENT_USER etc When we refer to

these keys in our C program code we omit the HKEY amp the underscores So to refer to the

HKEY_CURRENT_USER we use simply CurrentUser as the reference Well this reference is available

from the MicrosoftWin32Registry class This Registry class is available through the reference

using MicrosoftWin32

We use this reference to create a Key object An example of a Key object would be

MicrosoftWin32RegistryKey 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 = MicrosoftWin32RegistryClassesRootCreateSubKey(CSharp_Website)

Next we can set the Value of this Field using the SetValue() funtion See below

keySetValue(Really Yes)

httpwwwcode-kingsblogspotcom Page 14

The output shown below

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 15

Convert From Decimal to Binary System

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 gtgt

using System

namespace convert_decimal_to_binary

class Program

static void Main(string[] args)

int n c k

ConsoleWriteLine(Enter an integer in Decimal number systemn)

n = ConvertToInt32(ConsoleReadLine())

ConsoleWriteLine(nBinary Equivalent isn)

for (c = 31 c gt= 0 c--)

k = n gtgt c

if (ConvertToBoolean(k amp 1))

ConsoleWrite(1)

else

ConsoleWrite(0)

ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 16

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 TraceWriteLine() 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)

TraceWriteLine(message + message)

TraceWriteLine(member name + memberName)

TraceWriteLine(source file path + sourceFilePath)

TraceWriteLine(source line number + sourceLineNumber)

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

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 17

Reverse the Words in a Given 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 = strSourceSplit(new char[] ) string strReverse = stringEmpty for (int i = arySourceLength - 1 i gt= 0 i--) strReverse = strReverse + + arySource[i] ConsoleWriteLine(Original String nn + strSource) ConsoleWriteLine(nnReversed String nn + strReverse) return strReverse

httpwwwcode-kingsblogspotcom Page 18

static void Main(string[] args) reverseIt( I Am In Love With wwwcode-kingsblogspotcomcom) ConsoleWriteLine(nPress any key to continue) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 19

Named ArgumentsParameters in C

Named Arguments are an alternative way for specifing 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 specifiying 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

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 divisor5)

int a = remainder(divisor5 dividend 10)

Note that the position of the arguments have been interchanged both the above methods will

produce the same output ie they would set the value of a as 0(which is the remainder when

dividing 10 by 5)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 20

Optional ArgumentsParameters in C

This article will show you what is meant by Optional ArgumentsParameters in C 50 Optional

Arguments are mostly necessary when you specify functions that have a large number of

arguments

Optional Arguments are purely optional ie even if you do not specify them its perfectly OK

But it doesnt 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

The values that we supply in the function Definition are some constants These are the values

that are to be used in case no value is supplied in the function call These values are specified by

typing in variable expressions instead of just the declaration of variables

For example we would write

static void Func(Str = Default Value)

instead of static void Func(int Str)

If you didnt 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

When using this technique it is best that you have declared optional amp required parameters both

ie 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 = NA)

In the example above Name amp Age are required parameters The string Address is optional if

not specified then it would take the value NA meaning that 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)

Please Note

Do not Copy amp Paste code written here instead type it in your Development

Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 21

Transpose a Matrix

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

details

using System using SystemText using SystemThreadingTasks 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] ConsoleWriteLine(Enter the number of rows and columns of matrix ) m = ConvertToInt16(ConsoleReadLine()) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(Enter the elements of matrix n) for (c = 0 c lt m c++) for (d = 0 d lt n d++) matrix[c d] = ConvertToInt16(ConsoleReadLine()) for (c = 0 c lt m c++) for (d = 0 d lt n d++) transpose[d c] = matrix[c d]

httpwwwcode-kingsblogspotcom Page 22

ConsoleWriteLine(Transpose of entered matrix) for (c = 0 c lt n c++) for (d = 0 d lt m d++) ConsoleWrite( + transpose[c d]) ConsoleWriteLine() ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 23

Fibonacci Series

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 amp 1 The series goes on like

this

01123581321345589144233377helliphellip

Here we illustrate two techniques for the creation of the Fibonacci Series to n terms The For

Loop method amp 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 amp Second) Then we calculate the next term by adding these two terms amp setting a

new set of two new terms These terms are the Second amp Newest

using System using SystemText using SystemThreadingTasks namespace Fibonacci_series_Using_For_Loop class Program static void Main(string[] args) int n first = 0 second = 1 next c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First + n + terms of Fibonacci series are) for (c = 0 c lt n c++) if (c lt= 1) next = c

httpwwwcode-kingsblogspotcom Page 24

else next = first + second first = second second = next ConsoleWriteLine(next) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 25

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 amp two less than the number supplied In this way final

output value has each number added twice excluding 0 amp 1 Check the program below

using System using SystemText using SystemThreadingTasks namespace Fibonacci_Series_Recursion class Program static void Main(string[] args) int n i = 0 c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First 5 terms of Fibonacci series are) for (c = 1 c lt= n c++) ConsoleWriteLine(Fibonacci(i)) i++ ConsoleReadKey() static int Fibonacci(int n) if (n == 0) return 0 else if (n == 1) return 1 else return (Fibonacci(n - 1) + Fibonacci(n - 2))

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 26

Get Date Difference in C

Getting differences in two given dates is as easy as it gets The function used here is the

End_DateSubtract(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

using System using SystemText namespace Print_and_Get_Date_Difference_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) ConsoleWriteLine(The Date Today Is) DateTime DT = new DateTime() DT = DateTimeTodayDate ConsoleWriteLine(DTDateToString()) ConsoleWriteLine(Calculate the difference between two datesn) int year month day ConsoleWriteLine(Enter Start Date) ConsoleWriteLine(Enter Year)

httpwwwcode-kingsblogspotcom Page 27

year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_Start = new DateTime(yearmonthday) ConsoleWriteLine(nEnter End Date) ConsoleWriteLine(Enter Year) year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_End = new DateTime(year month day) TimeSpan timespan = DT_EndSubtract(DT_Start) ConsoleWriteLine(nThe Difference isn) ConsoleWriteLine(timespanTotalDaysToString() + Daysn) ConsoleWriteLine((timespanTotalDays 365)ToString() + Years) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 28

Obtain Local Host IP in C

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 SystemNet

namespace Obtain_IP_Address_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) String StringHost if (argsLength == 0) Getting Ip address of local machine First get the host name of local machine StringHost = SystemNetDnsGetHostName() ConsoleWriteLine(Local Machine Host Name is + StringHost) ConsoleWriteLine() else StringHost = args[0]

httpwwwcode-kingsblogspotcom Page 29

Then using host name get the IP address list IPHostEntry ipEntry = SystemNetDnsGetHostEntry(StringHost) IPAddress[] address = ipEntryAddressList for (int i = 0 i lt addressLength i++) ConsoleWriteLine() ConsoleWriteLine(IP Address Type 0 1 i address[i]ToString()) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 30

Monitor Turn OnOffStandBy in C

You might want to change your display settings in a running program The code behind requires

the Import of a Dll amp execution of a function SendMessage() by supplying 4 parameters The

value of the fourth parameter having values 0 1 amp 2 has the monitor in the states ON STAND

BY amp 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 SystemWindowsForms using SystemRuntimeInteropServices namespace Turn_Off_Monitor public partial class Form1 Form public Form1() InitializeComponent() [DllImport(user32dll)] public static extern IntPtr SendMessage(IntPtr hWnd uint 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(thisHandle WM_SYSCOMMAND b a) private void btnMonitorOff_Click(object sender EventArgs e) IntPtr a = new IntPtr(2) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

httpwwwcode-kingsblogspotcom Page 31

private void btnMonitorOn_Click(object sender EventArgs e) IntPtr a = new IntPtr(-1) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 32

Search Techniques Linear amp Binary

Searching is needed when we have a large array of some data or objects amp 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 amp finds the

position of elements Below you will find two search techniques viz Linear Search amp Binary

Search implemented in C The code is simple amp easy to understand amp can be modified as per

need

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 33

Code for Linear Search Technique in C Sharp

using System

using SystemText

using SystemThreadingTasks

namespace Linear_Search

class Program

static void Main(string[] args)

Int16[] array = new Int16[100]

Int16 search c number

ConsoleWriteLine(Enter the number of elements in arrayn)

number = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + numberToString() + numbersn)

for (c = 0 c lt number c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter the number to searchn)

search = ConvertToInt16(ConsoleReadLine())

for (c = 0 c lt number c++)

if (array[c] == search) if required element found

ConsoleWriteLine(searchToString() + is at locn + (c + 1)ToString() + n)

break

if (c == number)

ConsoleWriteLine(searchToString() + is not present in arrayn)

ConsoleReadLine()

httpwwwcode-kingsblogspotcom Page 34

Code for Binary Search Technique in C Sharp

namespace Binary_Search

class Program

static void Main(string[] args)

int c first last middle n search

Int16[] array = new Int16[100]

ConsoleWriteLine(Enter number of elementsn)

n = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + nToString() + integersn)

for (c = 0 c lt n c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter value to findn)

search = ConvertToInt16(ConsoleReadLine())

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

while (first lt= last)

if (array[middle] lt search)

first = middle + 1

else if (array[middle] == search)

ConsoleWriteLine(search + found at location + (middle + 1))

break

else

last = middle - 1

middle = (first + last) 2

if (first gt last)

ConsoleWriteLine(Not found + search + is not present in the list)

httpwwwcode-kingsblogspotcom Page 35

Working With Strings The 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 amp 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 txtLengthText = textBoxTextLengthToString() trkBar1Maximum = textBoxTextLength private void trackBar1_Scroll(object sender EventArgs e) Set the Max Value of second TrackBar trkBar2Maximum = textBoxTextLength - trkBar1Value textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString()

httpwwwcode-kingsblogspotcom Page 36

txtTotCharsText = trkBar2ValueToString() textBoxSelect()

Let us understand the working of this property with a simple String ABCDEFGH Suppose

you wanted to select the characters from between B amp C and Between F amp 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 ie

include A as well in the selection

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 ie a reduced

Maximum value

private void trackBar2_Scroll(object sender EventArgs e) textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString() txtTotCharsText = trkBar2ValueToString()

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 10: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 10

using System namespace Anagram_Test class Program static void Main(string[] args) ClassCheckAnagram cca = new ClassCheckAnagram() ConsoleWriteLine(Enter first stringn) string aa = ConsoleReadLine() char[] a = aaToCharArray() ConsoleWriteLine(nEnter second stringn) string bb = ConsoleReadLine() char[] b = bbToCharArray() int flag = ccacheck_anagram(a b) if (flag == 1) ConsoleWriteLine(nThey are anagramsn) else ConsoleWriteLine(nThey are not anagramsn) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 11

Using Indexers in C 5

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

obj1RollNumberVariable[0] obj1RollNumberVariable[1]

where RollNumberVariable would be the Integer variable

Now that you have learnt how to index your class amp 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 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 lt size i++) RollNumberVariable[i] = 0

httpwwwcode-kingsblogspotcom Page 12

public Int16 this[int pos] get return RollNumberVariable[pos] set RollNumberVariable[pos] = value using System namespace Indexers_Example class Program static void Main(string[] args) Int16 size = 5 Indexers obj1 = new Indexers(size) for (int i = 0 i lt size i++) obj1[i] = (short)i ConsoleWriteLine(nIndexer Outputn) for (int i = 0 i lt size i++) ConsoleWriteLine(Next Roll No + obj1[i]) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 13

How to Write into Windows Registry in C

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 as shown below

The Keys at the parent level are HKEY_CLASSES_ROOT HKEY_CURRENT_USER etc When we refer to

these keys in our C program code we omit the HKEY amp the underscores So to refer to the

HKEY_CURRENT_USER we use simply CurrentUser as the reference Well this reference is available

from the MicrosoftWin32Registry class This Registry class is available through the reference

using MicrosoftWin32

We use this reference to create a Key object An example of a Key object would be

MicrosoftWin32RegistryKey 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 = MicrosoftWin32RegistryClassesRootCreateSubKey(CSharp_Website)

Next we can set the Value of this Field using the SetValue() funtion See below

keySetValue(Really Yes)

httpwwwcode-kingsblogspotcom Page 14

The output shown below

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 15

Convert From Decimal to Binary System

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 gtgt

using System

namespace convert_decimal_to_binary

class Program

static void Main(string[] args)

int n c k

ConsoleWriteLine(Enter an integer in Decimal number systemn)

n = ConvertToInt32(ConsoleReadLine())

ConsoleWriteLine(nBinary Equivalent isn)

for (c = 31 c gt= 0 c--)

k = n gtgt c

if (ConvertToBoolean(k amp 1))

ConsoleWrite(1)

else

ConsoleWrite(0)

ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 16

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 TraceWriteLine() 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)

TraceWriteLine(message + message)

TraceWriteLine(member name + memberName)

TraceWriteLine(source file path + sourceFilePath)

TraceWriteLine(source line number + sourceLineNumber)

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

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 17

Reverse the Words in a Given 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 = strSourceSplit(new char[] ) string strReverse = stringEmpty for (int i = arySourceLength - 1 i gt= 0 i--) strReverse = strReverse + + arySource[i] ConsoleWriteLine(Original String nn + strSource) ConsoleWriteLine(nnReversed String nn + strReverse) return strReverse

httpwwwcode-kingsblogspotcom Page 18

static void Main(string[] args) reverseIt( I Am In Love With wwwcode-kingsblogspotcomcom) ConsoleWriteLine(nPress any key to continue) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 19

Named ArgumentsParameters in C

Named Arguments are an alternative way for specifing 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 specifiying 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

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 divisor5)

int a = remainder(divisor5 dividend 10)

Note that the position of the arguments have been interchanged both the above methods will

produce the same output ie they would set the value of a as 0(which is the remainder when

dividing 10 by 5)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 20

Optional ArgumentsParameters in C

This article will show you what is meant by Optional ArgumentsParameters in C 50 Optional

Arguments are mostly necessary when you specify functions that have a large number of

arguments

Optional Arguments are purely optional ie even if you do not specify them its perfectly OK

But it doesnt 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

The values that we supply in the function Definition are some constants These are the values

that are to be used in case no value is supplied in the function call These values are specified by

typing in variable expressions instead of just the declaration of variables

For example we would write

static void Func(Str = Default Value)

instead of static void Func(int Str)

If you didnt 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

When using this technique it is best that you have declared optional amp required parameters both

ie 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 = NA)

In the example above Name amp Age are required parameters The string Address is optional if

not specified then it would take the value NA meaning that 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)

Please Note

Do not Copy amp Paste code written here instead type it in your Development

Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 21

Transpose a Matrix

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

details

using System using SystemText using SystemThreadingTasks 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] ConsoleWriteLine(Enter the number of rows and columns of matrix ) m = ConvertToInt16(ConsoleReadLine()) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(Enter the elements of matrix n) for (c = 0 c lt m c++) for (d = 0 d lt n d++) matrix[c d] = ConvertToInt16(ConsoleReadLine()) for (c = 0 c lt m c++) for (d = 0 d lt n d++) transpose[d c] = matrix[c d]

httpwwwcode-kingsblogspotcom Page 22

ConsoleWriteLine(Transpose of entered matrix) for (c = 0 c lt n c++) for (d = 0 d lt m d++) ConsoleWrite( + transpose[c d]) ConsoleWriteLine() ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 23

Fibonacci Series

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 amp 1 The series goes on like

this

01123581321345589144233377helliphellip

Here we illustrate two techniques for the creation of the Fibonacci Series to n terms The For

Loop method amp 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 amp Second) Then we calculate the next term by adding these two terms amp setting a

new set of two new terms These terms are the Second amp Newest

using System using SystemText using SystemThreadingTasks namespace Fibonacci_series_Using_For_Loop class Program static void Main(string[] args) int n first = 0 second = 1 next c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First + n + terms of Fibonacci series are) for (c = 0 c lt n c++) if (c lt= 1) next = c

httpwwwcode-kingsblogspotcom Page 24

else next = first + second first = second second = next ConsoleWriteLine(next) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 25

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 amp two less than the number supplied In this way final

output value has each number added twice excluding 0 amp 1 Check the program below

using System using SystemText using SystemThreadingTasks namespace Fibonacci_Series_Recursion class Program static void Main(string[] args) int n i = 0 c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First 5 terms of Fibonacci series are) for (c = 1 c lt= n c++) ConsoleWriteLine(Fibonacci(i)) i++ ConsoleReadKey() static int Fibonacci(int n) if (n == 0) return 0 else if (n == 1) return 1 else return (Fibonacci(n - 1) + Fibonacci(n - 2))

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 26

Get Date Difference in C

Getting differences in two given dates is as easy as it gets The function used here is the

End_DateSubtract(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

using System using SystemText namespace Print_and_Get_Date_Difference_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) ConsoleWriteLine(The Date Today Is) DateTime DT = new DateTime() DT = DateTimeTodayDate ConsoleWriteLine(DTDateToString()) ConsoleWriteLine(Calculate the difference between two datesn) int year month day ConsoleWriteLine(Enter Start Date) ConsoleWriteLine(Enter Year)

httpwwwcode-kingsblogspotcom Page 27

year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_Start = new DateTime(yearmonthday) ConsoleWriteLine(nEnter End Date) ConsoleWriteLine(Enter Year) year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_End = new DateTime(year month day) TimeSpan timespan = DT_EndSubtract(DT_Start) ConsoleWriteLine(nThe Difference isn) ConsoleWriteLine(timespanTotalDaysToString() + Daysn) ConsoleWriteLine((timespanTotalDays 365)ToString() + Years) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 28

Obtain Local Host IP in C

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 SystemNet

namespace Obtain_IP_Address_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) String StringHost if (argsLength == 0) Getting Ip address of local machine First get the host name of local machine StringHost = SystemNetDnsGetHostName() ConsoleWriteLine(Local Machine Host Name is + StringHost) ConsoleWriteLine() else StringHost = args[0]

httpwwwcode-kingsblogspotcom Page 29

Then using host name get the IP address list IPHostEntry ipEntry = SystemNetDnsGetHostEntry(StringHost) IPAddress[] address = ipEntryAddressList for (int i = 0 i lt addressLength i++) ConsoleWriteLine() ConsoleWriteLine(IP Address Type 0 1 i address[i]ToString()) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 30

Monitor Turn OnOffStandBy in C

You might want to change your display settings in a running program The code behind requires

the Import of a Dll amp execution of a function SendMessage() by supplying 4 parameters The

value of the fourth parameter having values 0 1 amp 2 has the monitor in the states ON STAND

BY amp 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 SystemWindowsForms using SystemRuntimeInteropServices namespace Turn_Off_Monitor public partial class Form1 Form public Form1() InitializeComponent() [DllImport(user32dll)] public static extern IntPtr SendMessage(IntPtr hWnd uint 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(thisHandle WM_SYSCOMMAND b a) private void btnMonitorOff_Click(object sender EventArgs e) IntPtr a = new IntPtr(2) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

httpwwwcode-kingsblogspotcom Page 31

private void btnMonitorOn_Click(object sender EventArgs e) IntPtr a = new IntPtr(-1) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 32

Search Techniques Linear amp Binary

Searching is needed when we have a large array of some data or objects amp 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 amp finds the

position of elements Below you will find two search techniques viz Linear Search amp Binary

Search implemented in C The code is simple amp easy to understand amp can be modified as per

need

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 33

Code for Linear Search Technique in C Sharp

using System

using SystemText

using SystemThreadingTasks

namespace Linear_Search

class Program

static void Main(string[] args)

Int16[] array = new Int16[100]

Int16 search c number

ConsoleWriteLine(Enter the number of elements in arrayn)

number = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + numberToString() + numbersn)

for (c = 0 c lt number c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter the number to searchn)

search = ConvertToInt16(ConsoleReadLine())

for (c = 0 c lt number c++)

if (array[c] == search) if required element found

ConsoleWriteLine(searchToString() + is at locn + (c + 1)ToString() + n)

break

if (c == number)

ConsoleWriteLine(searchToString() + is not present in arrayn)

ConsoleReadLine()

httpwwwcode-kingsblogspotcom Page 34

Code for Binary Search Technique in C Sharp

namespace Binary_Search

class Program

static void Main(string[] args)

int c first last middle n search

Int16[] array = new Int16[100]

ConsoleWriteLine(Enter number of elementsn)

n = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + nToString() + integersn)

for (c = 0 c lt n c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter value to findn)

search = ConvertToInt16(ConsoleReadLine())

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

while (first lt= last)

if (array[middle] lt search)

first = middle + 1

else if (array[middle] == search)

ConsoleWriteLine(search + found at location + (middle + 1))

break

else

last = middle - 1

middle = (first + last) 2

if (first gt last)

ConsoleWriteLine(Not found + search + is not present in the list)

httpwwwcode-kingsblogspotcom Page 35

Working With Strings The 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 amp 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 txtLengthText = textBoxTextLengthToString() trkBar1Maximum = textBoxTextLength private void trackBar1_Scroll(object sender EventArgs e) Set the Max Value of second TrackBar trkBar2Maximum = textBoxTextLength - trkBar1Value textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString()

httpwwwcode-kingsblogspotcom Page 36

txtTotCharsText = trkBar2ValueToString() textBoxSelect()

Let us understand the working of this property with a simple String ABCDEFGH Suppose

you wanted to select the characters from between B amp C and Between F amp 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 ie

include A as well in the selection

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 ie a reduced

Maximum value

private void trackBar2_Scroll(object sender EventArgs e) textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString() txtTotCharsText = trkBar2ValueToString()

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 11: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 11

Using Indexers in C 5

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

obj1RollNumberVariable[0] obj1RollNumberVariable[1]

where RollNumberVariable would be the Integer variable

Now that you have learnt how to index your class amp 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 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 lt size i++) RollNumberVariable[i] = 0

httpwwwcode-kingsblogspotcom Page 12

public Int16 this[int pos] get return RollNumberVariable[pos] set RollNumberVariable[pos] = value using System namespace Indexers_Example class Program static void Main(string[] args) Int16 size = 5 Indexers obj1 = new Indexers(size) for (int i = 0 i lt size i++) obj1[i] = (short)i ConsoleWriteLine(nIndexer Outputn) for (int i = 0 i lt size i++) ConsoleWriteLine(Next Roll No + obj1[i]) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 13

How to Write into Windows Registry in C

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 as shown below

The Keys at the parent level are HKEY_CLASSES_ROOT HKEY_CURRENT_USER etc When we refer to

these keys in our C program code we omit the HKEY amp the underscores So to refer to the

HKEY_CURRENT_USER we use simply CurrentUser as the reference Well this reference is available

from the MicrosoftWin32Registry class This Registry class is available through the reference

using MicrosoftWin32

We use this reference to create a Key object An example of a Key object would be

MicrosoftWin32RegistryKey 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 = MicrosoftWin32RegistryClassesRootCreateSubKey(CSharp_Website)

Next we can set the Value of this Field using the SetValue() funtion See below

keySetValue(Really Yes)

httpwwwcode-kingsblogspotcom Page 14

The output shown below

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 15

Convert From Decimal to Binary System

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 gtgt

using System

namespace convert_decimal_to_binary

class Program

static void Main(string[] args)

int n c k

ConsoleWriteLine(Enter an integer in Decimal number systemn)

n = ConvertToInt32(ConsoleReadLine())

ConsoleWriteLine(nBinary Equivalent isn)

for (c = 31 c gt= 0 c--)

k = n gtgt c

if (ConvertToBoolean(k amp 1))

ConsoleWrite(1)

else

ConsoleWrite(0)

ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 16

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 TraceWriteLine() 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)

TraceWriteLine(message + message)

TraceWriteLine(member name + memberName)

TraceWriteLine(source file path + sourceFilePath)

TraceWriteLine(source line number + sourceLineNumber)

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

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 17

Reverse the Words in a Given 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 = strSourceSplit(new char[] ) string strReverse = stringEmpty for (int i = arySourceLength - 1 i gt= 0 i--) strReverse = strReverse + + arySource[i] ConsoleWriteLine(Original String nn + strSource) ConsoleWriteLine(nnReversed String nn + strReverse) return strReverse

httpwwwcode-kingsblogspotcom Page 18

static void Main(string[] args) reverseIt( I Am In Love With wwwcode-kingsblogspotcomcom) ConsoleWriteLine(nPress any key to continue) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 19

Named ArgumentsParameters in C

Named Arguments are an alternative way for specifing 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 specifiying 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

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 divisor5)

int a = remainder(divisor5 dividend 10)

Note that the position of the arguments have been interchanged both the above methods will

produce the same output ie they would set the value of a as 0(which is the remainder when

dividing 10 by 5)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 20

Optional ArgumentsParameters in C

This article will show you what is meant by Optional ArgumentsParameters in C 50 Optional

Arguments are mostly necessary when you specify functions that have a large number of

arguments

Optional Arguments are purely optional ie even if you do not specify them its perfectly OK

But it doesnt 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

The values that we supply in the function Definition are some constants These are the values

that are to be used in case no value is supplied in the function call These values are specified by

typing in variable expressions instead of just the declaration of variables

For example we would write

static void Func(Str = Default Value)

instead of static void Func(int Str)

If you didnt 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

When using this technique it is best that you have declared optional amp required parameters both

ie 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 = NA)

In the example above Name amp Age are required parameters The string Address is optional if

not specified then it would take the value NA meaning that 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)

Please Note

Do not Copy amp Paste code written here instead type it in your Development

Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 21

Transpose a Matrix

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

details

using System using SystemText using SystemThreadingTasks 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] ConsoleWriteLine(Enter the number of rows and columns of matrix ) m = ConvertToInt16(ConsoleReadLine()) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(Enter the elements of matrix n) for (c = 0 c lt m c++) for (d = 0 d lt n d++) matrix[c d] = ConvertToInt16(ConsoleReadLine()) for (c = 0 c lt m c++) for (d = 0 d lt n d++) transpose[d c] = matrix[c d]

httpwwwcode-kingsblogspotcom Page 22

ConsoleWriteLine(Transpose of entered matrix) for (c = 0 c lt n c++) for (d = 0 d lt m d++) ConsoleWrite( + transpose[c d]) ConsoleWriteLine() ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 23

Fibonacci Series

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 amp 1 The series goes on like

this

01123581321345589144233377helliphellip

Here we illustrate two techniques for the creation of the Fibonacci Series to n terms The For

Loop method amp 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 amp Second) Then we calculate the next term by adding these two terms amp setting a

new set of two new terms These terms are the Second amp Newest

using System using SystemText using SystemThreadingTasks namespace Fibonacci_series_Using_For_Loop class Program static void Main(string[] args) int n first = 0 second = 1 next c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First + n + terms of Fibonacci series are) for (c = 0 c lt n c++) if (c lt= 1) next = c

httpwwwcode-kingsblogspotcom Page 24

else next = first + second first = second second = next ConsoleWriteLine(next) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 25

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 amp two less than the number supplied In this way final

output value has each number added twice excluding 0 amp 1 Check the program below

using System using SystemText using SystemThreadingTasks namespace Fibonacci_Series_Recursion class Program static void Main(string[] args) int n i = 0 c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First 5 terms of Fibonacci series are) for (c = 1 c lt= n c++) ConsoleWriteLine(Fibonacci(i)) i++ ConsoleReadKey() static int Fibonacci(int n) if (n == 0) return 0 else if (n == 1) return 1 else return (Fibonacci(n - 1) + Fibonacci(n - 2))

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 26

Get Date Difference in C

Getting differences in two given dates is as easy as it gets The function used here is the

End_DateSubtract(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

using System using SystemText namespace Print_and_Get_Date_Difference_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) ConsoleWriteLine(The Date Today Is) DateTime DT = new DateTime() DT = DateTimeTodayDate ConsoleWriteLine(DTDateToString()) ConsoleWriteLine(Calculate the difference between two datesn) int year month day ConsoleWriteLine(Enter Start Date) ConsoleWriteLine(Enter Year)

httpwwwcode-kingsblogspotcom Page 27

year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_Start = new DateTime(yearmonthday) ConsoleWriteLine(nEnter End Date) ConsoleWriteLine(Enter Year) year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_End = new DateTime(year month day) TimeSpan timespan = DT_EndSubtract(DT_Start) ConsoleWriteLine(nThe Difference isn) ConsoleWriteLine(timespanTotalDaysToString() + Daysn) ConsoleWriteLine((timespanTotalDays 365)ToString() + Years) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 28

Obtain Local Host IP in C

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 SystemNet

namespace Obtain_IP_Address_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) String StringHost if (argsLength == 0) Getting Ip address of local machine First get the host name of local machine StringHost = SystemNetDnsGetHostName() ConsoleWriteLine(Local Machine Host Name is + StringHost) ConsoleWriteLine() else StringHost = args[0]

httpwwwcode-kingsblogspotcom Page 29

Then using host name get the IP address list IPHostEntry ipEntry = SystemNetDnsGetHostEntry(StringHost) IPAddress[] address = ipEntryAddressList for (int i = 0 i lt addressLength i++) ConsoleWriteLine() ConsoleWriteLine(IP Address Type 0 1 i address[i]ToString()) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 30

Monitor Turn OnOffStandBy in C

You might want to change your display settings in a running program The code behind requires

the Import of a Dll amp execution of a function SendMessage() by supplying 4 parameters The

value of the fourth parameter having values 0 1 amp 2 has the monitor in the states ON STAND

BY amp 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 SystemWindowsForms using SystemRuntimeInteropServices namespace Turn_Off_Monitor public partial class Form1 Form public Form1() InitializeComponent() [DllImport(user32dll)] public static extern IntPtr SendMessage(IntPtr hWnd uint 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(thisHandle WM_SYSCOMMAND b a) private void btnMonitorOff_Click(object sender EventArgs e) IntPtr a = new IntPtr(2) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

httpwwwcode-kingsblogspotcom Page 31

private void btnMonitorOn_Click(object sender EventArgs e) IntPtr a = new IntPtr(-1) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 32

Search Techniques Linear amp Binary

Searching is needed when we have a large array of some data or objects amp 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 amp finds the

position of elements Below you will find two search techniques viz Linear Search amp Binary

Search implemented in C The code is simple amp easy to understand amp can be modified as per

need

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 33

Code for Linear Search Technique in C Sharp

using System

using SystemText

using SystemThreadingTasks

namespace Linear_Search

class Program

static void Main(string[] args)

Int16[] array = new Int16[100]

Int16 search c number

ConsoleWriteLine(Enter the number of elements in arrayn)

number = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + numberToString() + numbersn)

for (c = 0 c lt number c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter the number to searchn)

search = ConvertToInt16(ConsoleReadLine())

for (c = 0 c lt number c++)

if (array[c] == search) if required element found

ConsoleWriteLine(searchToString() + is at locn + (c + 1)ToString() + n)

break

if (c == number)

ConsoleWriteLine(searchToString() + is not present in arrayn)

ConsoleReadLine()

httpwwwcode-kingsblogspotcom Page 34

Code for Binary Search Technique in C Sharp

namespace Binary_Search

class Program

static void Main(string[] args)

int c first last middle n search

Int16[] array = new Int16[100]

ConsoleWriteLine(Enter number of elementsn)

n = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + nToString() + integersn)

for (c = 0 c lt n c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter value to findn)

search = ConvertToInt16(ConsoleReadLine())

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

while (first lt= last)

if (array[middle] lt search)

first = middle + 1

else if (array[middle] == search)

ConsoleWriteLine(search + found at location + (middle + 1))

break

else

last = middle - 1

middle = (first + last) 2

if (first gt last)

ConsoleWriteLine(Not found + search + is not present in the list)

httpwwwcode-kingsblogspotcom Page 35

Working With Strings The 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 amp 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 txtLengthText = textBoxTextLengthToString() trkBar1Maximum = textBoxTextLength private void trackBar1_Scroll(object sender EventArgs e) Set the Max Value of second TrackBar trkBar2Maximum = textBoxTextLength - trkBar1Value textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString()

httpwwwcode-kingsblogspotcom Page 36

txtTotCharsText = trkBar2ValueToString() textBoxSelect()

Let us understand the working of this property with a simple String ABCDEFGH Suppose

you wanted to select the characters from between B amp C and Between F amp 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 ie

include A as well in the selection

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 ie a reduced

Maximum value

private void trackBar2_Scroll(object sender EventArgs e) textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString() txtTotCharsText = trkBar2ValueToString()

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 12: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 12

public Int16 this[int pos] get return RollNumberVariable[pos] set RollNumberVariable[pos] = value using System namespace Indexers_Example class Program static void Main(string[] args) Int16 size = 5 Indexers obj1 = new Indexers(size) for (int i = 0 i lt size i++) obj1[i] = (short)i ConsoleWriteLine(nIndexer Outputn) for (int i = 0 i lt size i++) ConsoleWriteLine(Next Roll No + obj1[i]) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 13

How to Write into Windows Registry in C

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 as shown below

The Keys at the parent level are HKEY_CLASSES_ROOT HKEY_CURRENT_USER etc When we refer to

these keys in our C program code we omit the HKEY amp the underscores So to refer to the

HKEY_CURRENT_USER we use simply CurrentUser as the reference Well this reference is available

from the MicrosoftWin32Registry class This Registry class is available through the reference

using MicrosoftWin32

We use this reference to create a Key object An example of a Key object would be

MicrosoftWin32RegistryKey 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 = MicrosoftWin32RegistryClassesRootCreateSubKey(CSharp_Website)

Next we can set the Value of this Field using the SetValue() funtion See below

keySetValue(Really Yes)

httpwwwcode-kingsblogspotcom Page 14

The output shown below

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 15

Convert From Decimal to Binary System

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 gtgt

using System

namespace convert_decimal_to_binary

class Program

static void Main(string[] args)

int n c k

ConsoleWriteLine(Enter an integer in Decimal number systemn)

n = ConvertToInt32(ConsoleReadLine())

ConsoleWriteLine(nBinary Equivalent isn)

for (c = 31 c gt= 0 c--)

k = n gtgt c

if (ConvertToBoolean(k amp 1))

ConsoleWrite(1)

else

ConsoleWrite(0)

ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 16

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 TraceWriteLine() 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)

TraceWriteLine(message + message)

TraceWriteLine(member name + memberName)

TraceWriteLine(source file path + sourceFilePath)

TraceWriteLine(source line number + sourceLineNumber)

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

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 17

Reverse the Words in a Given 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 = strSourceSplit(new char[] ) string strReverse = stringEmpty for (int i = arySourceLength - 1 i gt= 0 i--) strReverse = strReverse + + arySource[i] ConsoleWriteLine(Original String nn + strSource) ConsoleWriteLine(nnReversed String nn + strReverse) return strReverse

httpwwwcode-kingsblogspotcom Page 18

static void Main(string[] args) reverseIt( I Am In Love With wwwcode-kingsblogspotcomcom) ConsoleWriteLine(nPress any key to continue) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 19

Named ArgumentsParameters in C

Named Arguments are an alternative way for specifing 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 specifiying 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

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 divisor5)

int a = remainder(divisor5 dividend 10)

Note that the position of the arguments have been interchanged both the above methods will

produce the same output ie they would set the value of a as 0(which is the remainder when

dividing 10 by 5)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 20

Optional ArgumentsParameters in C

This article will show you what is meant by Optional ArgumentsParameters in C 50 Optional

Arguments are mostly necessary when you specify functions that have a large number of

arguments

Optional Arguments are purely optional ie even if you do not specify them its perfectly OK

But it doesnt 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

The values that we supply in the function Definition are some constants These are the values

that are to be used in case no value is supplied in the function call These values are specified by

typing in variable expressions instead of just the declaration of variables

For example we would write

static void Func(Str = Default Value)

instead of static void Func(int Str)

If you didnt 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

When using this technique it is best that you have declared optional amp required parameters both

ie 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 = NA)

In the example above Name amp Age are required parameters The string Address is optional if

not specified then it would take the value NA meaning that 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)

Please Note

Do not Copy amp Paste code written here instead type it in your Development

Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 21

Transpose a Matrix

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

details

using System using SystemText using SystemThreadingTasks 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] ConsoleWriteLine(Enter the number of rows and columns of matrix ) m = ConvertToInt16(ConsoleReadLine()) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(Enter the elements of matrix n) for (c = 0 c lt m c++) for (d = 0 d lt n d++) matrix[c d] = ConvertToInt16(ConsoleReadLine()) for (c = 0 c lt m c++) for (d = 0 d lt n d++) transpose[d c] = matrix[c d]

httpwwwcode-kingsblogspotcom Page 22

ConsoleWriteLine(Transpose of entered matrix) for (c = 0 c lt n c++) for (d = 0 d lt m d++) ConsoleWrite( + transpose[c d]) ConsoleWriteLine() ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 23

Fibonacci Series

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 amp 1 The series goes on like

this

01123581321345589144233377helliphellip

Here we illustrate two techniques for the creation of the Fibonacci Series to n terms The For

Loop method amp 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 amp Second) Then we calculate the next term by adding these two terms amp setting a

new set of two new terms These terms are the Second amp Newest

using System using SystemText using SystemThreadingTasks namespace Fibonacci_series_Using_For_Loop class Program static void Main(string[] args) int n first = 0 second = 1 next c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First + n + terms of Fibonacci series are) for (c = 0 c lt n c++) if (c lt= 1) next = c

httpwwwcode-kingsblogspotcom Page 24

else next = first + second first = second second = next ConsoleWriteLine(next) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 25

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 amp two less than the number supplied In this way final

output value has each number added twice excluding 0 amp 1 Check the program below

using System using SystemText using SystemThreadingTasks namespace Fibonacci_Series_Recursion class Program static void Main(string[] args) int n i = 0 c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First 5 terms of Fibonacci series are) for (c = 1 c lt= n c++) ConsoleWriteLine(Fibonacci(i)) i++ ConsoleReadKey() static int Fibonacci(int n) if (n == 0) return 0 else if (n == 1) return 1 else return (Fibonacci(n - 1) + Fibonacci(n - 2))

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 26

Get Date Difference in C

Getting differences in two given dates is as easy as it gets The function used here is the

End_DateSubtract(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

using System using SystemText namespace Print_and_Get_Date_Difference_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) ConsoleWriteLine(The Date Today Is) DateTime DT = new DateTime() DT = DateTimeTodayDate ConsoleWriteLine(DTDateToString()) ConsoleWriteLine(Calculate the difference between two datesn) int year month day ConsoleWriteLine(Enter Start Date) ConsoleWriteLine(Enter Year)

httpwwwcode-kingsblogspotcom Page 27

year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_Start = new DateTime(yearmonthday) ConsoleWriteLine(nEnter End Date) ConsoleWriteLine(Enter Year) year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_End = new DateTime(year month day) TimeSpan timespan = DT_EndSubtract(DT_Start) ConsoleWriteLine(nThe Difference isn) ConsoleWriteLine(timespanTotalDaysToString() + Daysn) ConsoleWriteLine((timespanTotalDays 365)ToString() + Years) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 28

Obtain Local Host IP in C

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 SystemNet

namespace Obtain_IP_Address_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) String StringHost if (argsLength == 0) Getting Ip address of local machine First get the host name of local machine StringHost = SystemNetDnsGetHostName() ConsoleWriteLine(Local Machine Host Name is + StringHost) ConsoleWriteLine() else StringHost = args[0]

httpwwwcode-kingsblogspotcom Page 29

Then using host name get the IP address list IPHostEntry ipEntry = SystemNetDnsGetHostEntry(StringHost) IPAddress[] address = ipEntryAddressList for (int i = 0 i lt addressLength i++) ConsoleWriteLine() ConsoleWriteLine(IP Address Type 0 1 i address[i]ToString()) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 30

Monitor Turn OnOffStandBy in C

You might want to change your display settings in a running program The code behind requires

the Import of a Dll amp execution of a function SendMessage() by supplying 4 parameters The

value of the fourth parameter having values 0 1 amp 2 has the monitor in the states ON STAND

BY amp 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 SystemWindowsForms using SystemRuntimeInteropServices namespace Turn_Off_Monitor public partial class Form1 Form public Form1() InitializeComponent() [DllImport(user32dll)] public static extern IntPtr SendMessage(IntPtr hWnd uint 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(thisHandle WM_SYSCOMMAND b a) private void btnMonitorOff_Click(object sender EventArgs e) IntPtr a = new IntPtr(2) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

httpwwwcode-kingsblogspotcom Page 31

private void btnMonitorOn_Click(object sender EventArgs e) IntPtr a = new IntPtr(-1) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 32

Search Techniques Linear amp Binary

Searching is needed when we have a large array of some data or objects amp 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 amp finds the

position of elements Below you will find two search techniques viz Linear Search amp Binary

Search implemented in C The code is simple amp easy to understand amp can be modified as per

need

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 33

Code for Linear Search Technique in C Sharp

using System

using SystemText

using SystemThreadingTasks

namespace Linear_Search

class Program

static void Main(string[] args)

Int16[] array = new Int16[100]

Int16 search c number

ConsoleWriteLine(Enter the number of elements in arrayn)

number = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + numberToString() + numbersn)

for (c = 0 c lt number c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter the number to searchn)

search = ConvertToInt16(ConsoleReadLine())

for (c = 0 c lt number c++)

if (array[c] == search) if required element found

ConsoleWriteLine(searchToString() + is at locn + (c + 1)ToString() + n)

break

if (c == number)

ConsoleWriteLine(searchToString() + is not present in arrayn)

ConsoleReadLine()

httpwwwcode-kingsblogspotcom Page 34

Code for Binary Search Technique in C Sharp

namespace Binary_Search

class Program

static void Main(string[] args)

int c first last middle n search

Int16[] array = new Int16[100]

ConsoleWriteLine(Enter number of elementsn)

n = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + nToString() + integersn)

for (c = 0 c lt n c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter value to findn)

search = ConvertToInt16(ConsoleReadLine())

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

while (first lt= last)

if (array[middle] lt search)

first = middle + 1

else if (array[middle] == search)

ConsoleWriteLine(search + found at location + (middle + 1))

break

else

last = middle - 1

middle = (first + last) 2

if (first gt last)

ConsoleWriteLine(Not found + search + is not present in the list)

httpwwwcode-kingsblogspotcom Page 35

Working With Strings The 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 amp 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 txtLengthText = textBoxTextLengthToString() trkBar1Maximum = textBoxTextLength private void trackBar1_Scroll(object sender EventArgs e) Set the Max Value of second TrackBar trkBar2Maximum = textBoxTextLength - trkBar1Value textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString()

httpwwwcode-kingsblogspotcom Page 36

txtTotCharsText = trkBar2ValueToString() textBoxSelect()

Let us understand the working of this property with a simple String ABCDEFGH Suppose

you wanted to select the characters from between B amp C and Between F amp 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 ie

include A as well in the selection

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 ie a reduced

Maximum value

private void trackBar2_Scroll(object sender EventArgs e) textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString() txtTotCharsText = trkBar2ValueToString()

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 13: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 13

How to Write into Windows Registry in C

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 as shown below

The Keys at the parent level are HKEY_CLASSES_ROOT HKEY_CURRENT_USER etc When we refer to

these keys in our C program code we omit the HKEY amp the underscores So to refer to the

HKEY_CURRENT_USER we use simply CurrentUser as the reference Well this reference is available

from the MicrosoftWin32Registry class This Registry class is available through the reference

using MicrosoftWin32

We use this reference to create a Key object An example of a Key object would be

MicrosoftWin32RegistryKey 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 = MicrosoftWin32RegistryClassesRootCreateSubKey(CSharp_Website)

Next we can set the Value of this Field using the SetValue() funtion See below

keySetValue(Really Yes)

httpwwwcode-kingsblogspotcom Page 14

The output shown below

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 15

Convert From Decimal to Binary System

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 gtgt

using System

namespace convert_decimal_to_binary

class Program

static void Main(string[] args)

int n c k

ConsoleWriteLine(Enter an integer in Decimal number systemn)

n = ConvertToInt32(ConsoleReadLine())

ConsoleWriteLine(nBinary Equivalent isn)

for (c = 31 c gt= 0 c--)

k = n gtgt c

if (ConvertToBoolean(k amp 1))

ConsoleWrite(1)

else

ConsoleWrite(0)

ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 16

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 TraceWriteLine() 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)

TraceWriteLine(message + message)

TraceWriteLine(member name + memberName)

TraceWriteLine(source file path + sourceFilePath)

TraceWriteLine(source line number + sourceLineNumber)

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

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 17

Reverse the Words in a Given 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 = strSourceSplit(new char[] ) string strReverse = stringEmpty for (int i = arySourceLength - 1 i gt= 0 i--) strReverse = strReverse + + arySource[i] ConsoleWriteLine(Original String nn + strSource) ConsoleWriteLine(nnReversed String nn + strReverse) return strReverse

httpwwwcode-kingsblogspotcom Page 18

static void Main(string[] args) reverseIt( I Am In Love With wwwcode-kingsblogspotcomcom) ConsoleWriteLine(nPress any key to continue) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 19

Named ArgumentsParameters in C

Named Arguments are an alternative way for specifing 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 specifiying 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

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 divisor5)

int a = remainder(divisor5 dividend 10)

Note that the position of the arguments have been interchanged both the above methods will

produce the same output ie they would set the value of a as 0(which is the remainder when

dividing 10 by 5)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 20

Optional ArgumentsParameters in C

This article will show you what is meant by Optional ArgumentsParameters in C 50 Optional

Arguments are mostly necessary when you specify functions that have a large number of

arguments

Optional Arguments are purely optional ie even if you do not specify them its perfectly OK

But it doesnt 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

The values that we supply in the function Definition are some constants These are the values

that are to be used in case no value is supplied in the function call These values are specified by

typing in variable expressions instead of just the declaration of variables

For example we would write

static void Func(Str = Default Value)

instead of static void Func(int Str)

If you didnt 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

When using this technique it is best that you have declared optional amp required parameters both

ie 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 = NA)

In the example above Name amp Age are required parameters The string Address is optional if

not specified then it would take the value NA meaning that 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)

Please Note

Do not Copy amp Paste code written here instead type it in your Development

Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 21

Transpose a Matrix

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

details

using System using SystemText using SystemThreadingTasks 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] ConsoleWriteLine(Enter the number of rows and columns of matrix ) m = ConvertToInt16(ConsoleReadLine()) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(Enter the elements of matrix n) for (c = 0 c lt m c++) for (d = 0 d lt n d++) matrix[c d] = ConvertToInt16(ConsoleReadLine()) for (c = 0 c lt m c++) for (d = 0 d lt n d++) transpose[d c] = matrix[c d]

httpwwwcode-kingsblogspotcom Page 22

ConsoleWriteLine(Transpose of entered matrix) for (c = 0 c lt n c++) for (d = 0 d lt m d++) ConsoleWrite( + transpose[c d]) ConsoleWriteLine() ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 23

Fibonacci Series

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 amp 1 The series goes on like

this

01123581321345589144233377helliphellip

Here we illustrate two techniques for the creation of the Fibonacci Series to n terms The For

Loop method amp 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 amp Second) Then we calculate the next term by adding these two terms amp setting a

new set of two new terms These terms are the Second amp Newest

using System using SystemText using SystemThreadingTasks namespace Fibonacci_series_Using_For_Loop class Program static void Main(string[] args) int n first = 0 second = 1 next c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First + n + terms of Fibonacci series are) for (c = 0 c lt n c++) if (c lt= 1) next = c

httpwwwcode-kingsblogspotcom Page 24

else next = first + second first = second second = next ConsoleWriteLine(next) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 25

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 amp two less than the number supplied In this way final

output value has each number added twice excluding 0 amp 1 Check the program below

using System using SystemText using SystemThreadingTasks namespace Fibonacci_Series_Recursion class Program static void Main(string[] args) int n i = 0 c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First 5 terms of Fibonacci series are) for (c = 1 c lt= n c++) ConsoleWriteLine(Fibonacci(i)) i++ ConsoleReadKey() static int Fibonacci(int n) if (n == 0) return 0 else if (n == 1) return 1 else return (Fibonacci(n - 1) + Fibonacci(n - 2))

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 26

Get Date Difference in C

Getting differences in two given dates is as easy as it gets The function used here is the

End_DateSubtract(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

using System using SystemText namespace Print_and_Get_Date_Difference_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) ConsoleWriteLine(The Date Today Is) DateTime DT = new DateTime() DT = DateTimeTodayDate ConsoleWriteLine(DTDateToString()) ConsoleWriteLine(Calculate the difference between two datesn) int year month day ConsoleWriteLine(Enter Start Date) ConsoleWriteLine(Enter Year)

httpwwwcode-kingsblogspotcom Page 27

year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_Start = new DateTime(yearmonthday) ConsoleWriteLine(nEnter End Date) ConsoleWriteLine(Enter Year) year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_End = new DateTime(year month day) TimeSpan timespan = DT_EndSubtract(DT_Start) ConsoleWriteLine(nThe Difference isn) ConsoleWriteLine(timespanTotalDaysToString() + Daysn) ConsoleWriteLine((timespanTotalDays 365)ToString() + Years) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 28

Obtain Local Host IP in C

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 SystemNet

namespace Obtain_IP_Address_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) String StringHost if (argsLength == 0) Getting Ip address of local machine First get the host name of local machine StringHost = SystemNetDnsGetHostName() ConsoleWriteLine(Local Machine Host Name is + StringHost) ConsoleWriteLine() else StringHost = args[0]

httpwwwcode-kingsblogspotcom Page 29

Then using host name get the IP address list IPHostEntry ipEntry = SystemNetDnsGetHostEntry(StringHost) IPAddress[] address = ipEntryAddressList for (int i = 0 i lt addressLength i++) ConsoleWriteLine() ConsoleWriteLine(IP Address Type 0 1 i address[i]ToString()) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 30

Monitor Turn OnOffStandBy in C

You might want to change your display settings in a running program The code behind requires

the Import of a Dll amp execution of a function SendMessage() by supplying 4 parameters The

value of the fourth parameter having values 0 1 amp 2 has the monitor in the states ON STAND

BY amp 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 SystemWindowsForms using SystemRuntimeInteropServices namespace Turn_Off_Monitor public partial class Form1 Form public Form1() InitializeComponent() [DllImport(user32dll)] public static extern IntPtr SendMessage(IntPtr hWnd uint 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(thisHandle WM_SYSCOMMAND b a) private void btnMonitorOff_Click(object sender EventArgs e) IntPtr a = new IntPtr(2) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

httpwwwcode-kingsblogspotcom Page 31

private void btnMonitorOn_Click(object sender EventArgs e) IntPtr a = new IntPtr(-1) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 32

Search Techniques Linear amp Binary

Searching is needed when we have a large array of some data or objects amp 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 amp finds the

position of elements Below you will find two search techniques viz Linear Search amp Binary

Search implemented in C The code is simple amp easy to understand amp can be modified as per

need

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 33

Code for Linear Search Technique in C Sharp

using System

using SystemText

using SystemThreadingTasks

namespace Linear_Search

class Program

static void Main(string[] args)

Int16[] array = new Int16[100]

Int16 search c number

ConsoleWriteLine(Enter the number of elements in arrayn)

number = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + numberToString() + numbersn)

for (c = 0 c lt number c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter the number to searchn)

search = ConvertToInt16(ConsoleReadLine())

for (c = 0 c lt number c++)

if (array[c] == search) if required element found

ConsoleWriteLine(searchToString() + is at locn + (c + 1)ToString() + n)

break

if (c == number)

ConsoleWriteLine(searchToString() + is not present in arrayn)

ConsoleReadLine()

httpwwwcode-kingsblogspotcom Page 34

Code for Binary Search Technique in C Sharp

namespace Binary_Search

class Program

static void Main(string[] args)

int c first last middle n search

Int16[] array = new Int16[100]

ConsoleWriteLine(Enter number of elementsn)

n = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + nToString() + integersn)

for (c = 0 c lt n c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter value to findn)

search = ConvertToInt16(ConsoleReadLine())

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

while (first lt= last)

if (array[middle] lt search)

first = middle + 1

else if (array[middle] == search)

ConsoleWriteLine(search + found at location + (middle + 1))

break

else

last = middle - 1

middle = (first + last) 2

if (first gt last)

ConsoleWriteLine(Not found + search + is not present in the list)

httpwwwcode-kingsblogspotcom Page 35

Working With Strings The 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 amp 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 txtLengthText = textBoxTextLengthToString() trkBar1Maximum = textBoxTextLength private void trackBar1_Scroll(object sender EventArgs e) Set the Max Value of second TrackBar trkBar2Maximum = textBoxTextLength - trkBar1Value textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString()

httpwwwcode-kingsblogspotcom Page 36

txtTotCharsText = trkBar2ValueToString() textBoxSelect()

Let us understand the working of this property with a simple String ABCDEFGH Suppose

you wanted to select the characters from between B amp C and Between F amp 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 ie

include A as well in the selection

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 ie a reduced

Maximum value

private void trackBar2_Scroll(object sender EventArgs e) textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString() txtTotCharsText = trkBar2ValueToString()

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 14: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 14

The output shown below

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 15

Convert From Decimal to Binary System

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 gtgt

using System

namespace convert_decimal_to_binary

class Program

static void Main(string[] args)

int n c k

ConsoleWriteLine(Enter an integer in Decimal number systemn)

n = ConvertToInt32(ConsoleReadLine())

ConsoleWriteLine(nBinary Equivalent isn)

for (c = 31 c gt= 0 c--)

k = n gtgt c

if (ConvertToBoolean(k amp 1))

ConsoleWrite(1)

else

ConsoleWrite(0)

ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 16

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 TraceWriteLine() 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)

TraceWriteLine(message + message)

TraceWriteLine(member name + memberName)

TraceWriteLine(source file path + sourceFilePath)

TraceWriteLine(source line number + sourceLineNumber)

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

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 17

Reverse the Words in a Given 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 = strSourceSplit(new char[] ) string strReverse = stringEmpty for (int i = arySourceLength - 1 i gt= 0 i--) strReverse = strReverse + + arySource[i] ConsoleWriteLine(Original String nn + strSource) ConsoleWriteLine(nnReversed String nn + strReverse) return strReverse

httpwwwcode-kingsblogspotcom Page 18

static void Main(string[] args) reverseIt( I Am In Love With wwwcode-kingsblogspotcomcom) ConsoleWriteLine(nPress any key to continue) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 19

Named ArgumentsParameters in C

Named Arguments are an alternative way for specifing 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 specifiying 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

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 divisor5)

int a = remainder(divisor5 dividend 10)

Note that the position of the arguments have been interchanged both the above methods will

produce the same output ie they would set the value of a as 0(which is the remainder when

dividing 10 by 5)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 20

Optional ArgumentsParameters in C

This article will show you what is meant by Optional ArgumentsParameters in C 50 Optional

Arguments are mostly necessary when you specify functions that have a large number of

arguments

Optional Arguments are purely optional ie even if you do not specify them its perfectly OK

But it doesnt 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

The values that we supply in the function Definition are some constants These are the values

that are to be used in case no value is supplied in the function call These values are specified by

typing in variable expressions instead of just the declaration of variables

For example we would write

static void Func(Str = Default Value)

instead of static void Func(int Str)

If you didnt 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

When using this technique it is best that you have declared optional amp required parameters both

ie 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 = NA)

In the example above Name amp Age are required parameters The string Address is optional if

not specified then it would take the value NA meaning that 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)

Please Note

Do not Copy amp Paste code written here instead type it in your Development

Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 21

Transpose a Matrix

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

details

using System using SystemText using SystemThreadingTasks 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] ConsoleWriteLine(Enter the number of rows and columns of matrix ) m = ConvertToInt16(ConsoleReadLine()) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(Enter the elements of matrix n) for (c = 0 c lt m c++) for (d = 0 d lt n d++) matrix[c d] = ConvertToInt16(ConsoleReadLine()) for (c = 0 c lt m c++) for (d = 0 d lt n d++) transpose[d c] = matrix[c d]

httpwwwcode-kingsblogspotcom Page 22

ConsoleWriteLine(Transpose of entered matrix) for (c = 0 c lt n c++) for (d = 0 d lt m d++) ConsoleWrite( + transpose[c d]) ConsoleWriteLine() ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 23

Fibonacci Series

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 amp 1 The series goes on like

this

01123581321345589144233377helliphellip

Here we illustrate two techniques for the creation of the Fibonacci Series to n terms The For

Loop method amp 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 amp Second) Then we calculate the next term by adding these two terms amp setting a

new set of two new terms These terms are the Second amp Newest

using System using SystemText using SystemThreadingTasks namespace Fibonacci_series_Using_For_Loop class Program static void Main(string[] args) int n first = 0 second = 1 next c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First + n + terms of Fibonacci series are) for (c = 0 c lt n c++) if (c lt= 1) next = c

httpwwwcode-kingsblogspotcom Page 24

else next = first + second first = second second = next ConsoleWriteLine(next) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 25

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 amp two less than the number supplied In this way final

output value has each number added twice excluding 0 amp 1 Check the program below

using System using SystemText using SystemThreadingTasks namespace Fibonacci_Series_Recursion class Program static void Main(string[] args) int n i = 0 c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First 5 terms of Fibonacci series are) for (c = 1 c lt= n c++) ConsoleWriteLine(Fibonacci(i)) i++ ConsoleReadKey() static int Fibonacci(int n) if (n == 0) return 0 else if (n == 1) return 1 else return (Fibonacci(n - 1) + Fibonacci(n - 2))

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 26

Get Date Difference in C

Getting differences in two given dates is as easy as it gets The function used here is the

End_DateSubtract(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

using System using SystemText namespace Print_and_Get_Date_Difference_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) ConsoleWriteLine(The Date Today Is) DateTime DT = new DateTime() DT = DateTimeTodayDate ConsoleWriteLine(DTDateToString()) ConsoleWriteLine(Calculate the difference between two datesn) int year month day ConsoleWriteLine(Enter Start Date) ConsoleWriteLine(Enter Year)

httpwwwcode-kingsblogspotcom Page 27

year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_Start = new DateTime(yearmonthday) ConsoleWriteLine(nEnter End Date) ConsoleWriteLine(Enter Year) year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_End = new DateTime(year month day) TimeSpan timespan = DT_EndSubtract(DT_Start) ConsoleWriteLine(nThe Difference isn) ConsoleWriteLine(timespanTotalDaysToString() + Daysn) ConsoleWriteLine((timespanTotalDays 365)ToString() + Years) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 28

Obtain Local Host IP in C

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 SystemNet

namespace Obtain_IP_Address_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) String StringHost if (argsLength == 0) Getting Ip address of local machine First get the host name of local machine StringHost = SystemNetDnsGetHostName() ConsoleWriteLine(Local Machine Host Name is + StringHost) ConsoleWriteLine() else StringHost = args[0]

httpwwwcode-kingsblogspotcom Page 29

Then using host name get the IP address list IPHostEntry ipEntry = SystemNetDnsGetHostEntry(StringHost) IPAddress[] address = ipEntryAddressList for (int i = 0 i lt addressLength i++) ConsoleWriteLine() ConsoleWriteLine(IP Address Type 0 1 i address[i]ToString()) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 30

Monitor Turn OnOffStandBy in C

You might want to change your display settings in a running program The code behind requires

the Import of a Dll amp execution of a function SendMessage() by supplying 4 parameters The

value of the fourth parameter having values 0 1 amp 2 has the monitor in the states ON STAND

BY amp 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 SystemWindowsForms using SystemRuntimeInteropServices namespace Turn_Off_Monitor public partial class Form1 Form public Form1() InitializeComponent() [DllImport(user32dll)] public static extern IntPtr SendMessage(IntPtr hWnd uint 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(thisHandle WM_SYSCOMMAND b a) private void btnMonitorOff_Click(object sender EventArgs e) IntPtr a = new IntPtr(2) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

httpwwwcode-kingsblogspotcom Page 31

private void btnMonitorOn_Click(object sender EventArgs e) IntPtr a = new IntPtr(-1) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 32

Search Techniques Linear amp Binary

Searching is needed when we have a large array of some data or objects amp 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 amp finds the

position of elements Below you will find two search techniques viz Linear Search amp Binary

Search implemented in C The code is simple amp easy to understand amp can be modified as per

need

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 33

Code for Linear Search Technique in C Sharp

using System

using SystemText

using SystemThreadingTasks

namespace Linear_Search

class Program

static void Main(string[] args)

Int16[] array = new Int16[100]

Int16 search c number

ConsoleWriteLine(Enter the number of elements in arrayn)

number = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + numberToString() + numbersn)

for (c = 0 c lt number c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter the number to searchn)

search = ConvertToInt16(ConsoleReadLine())

for (c = 0 c lt number c++)

if (array[c] == search) if required element found

ConsoleWriteLine(searchToString() + is at locn + (c + 1)ToString() + n)

break

if (c == number)

ConsoleWriteLine(searchToString() + is not present in arrayn)

ConsoleReadLine()

httpwwwcode-kingsblogspotcom Page 34

Code for Binary Search Technique in C Sharp

namespace Binary_Search

class Program

static void Main(string[] args)

int c first last middle n search

Int16[] array = new Int16[100]

ConsoleWriteLine(Enter number of elementsn)

n = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + nToString() + integersn)

for (c = 0 c lt n c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter value to findn)

search = ConvertToInt16(ConsoleReadLine())

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

while (first lt= last)

if (array[middle] lt search)

first = middle + 1

else if (array[middle] == search)

ConsoleWriteLine(search + found at location + (middle + 1))

break

else

last = middle - 1

middle = (first + last) 2

if (first gt last)

ConsoleWriteLine(Not found + search + is not present in the list)

httpwwwcode-kingsblogspotcom Page 35

Working With Strings The 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 amp 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 txtLengthText = textBoxTextLengthToString() trkBar1Maximum = textBoxTextLength private void trackBar1_Scroll(object sender EventArgs e) Set the Max Value of second TrackBar trkBar2Maximum = textBoxTextLength - trkBar1Value textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString()

httpwwwcode-kingsblogspotcom Page 36

txtTotCharsText = trkBar2ValueToString() textBoxSelect()

Let us understand the working of this property with a simple String ABCDEFGH Suppose

you wanted to select the characters from between B amp C and Between F amp 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 ie

include A as well in the selection

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 ie a reduced

Maximum value

private void trackBar2_Scroll(object sender EventArgs e) textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString() txtTotCharsText = trkBar2ValueToString()

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 15: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 15

Convert From Decimal to Binary System

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 gtgt

using System

namespace convert_decimal_to_binary

class Program

static void Main(string[] args)

int n c k

ConsoleWriteLine(Enter an integer in Decimal number systemn)

n = ConvertToInt32(ConsoleReadLine())

ConsoleWriteLine(nBinary Equivalent isn)

for (c = 31 c gt= 0 c--)

k = n gtgt c

if (ConvertToBoolean(k amp 1))

ConsoleWrite(1)

else

ConsoleWrite(0)

ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 16

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 TraceWriteLine() 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)

TraceWriteLine(message + message)

TraceWriteLine(member name + memberName)

TraceWriteLine(source file path + sourceFilePath)

TraceWriteLine(source line number + sourceLineNumber)

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

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 17

Reverse the Words in a Given 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 = strSourceSplit(new char[] ) string strReverse = stringEmpty for (int i = arySourceLength - 1 i gt= 0 i--) strReverse = strReverse + + arySource[i] ConsoleWriteLine(Original String nn + strSource) ConsoleWriteLine(nnReversed String nn + strReverse) return strReverse

httpwwwcode-kingsblogspotcom Page 18

static void Main(string[] args) reverseIt( I Am In Love With wwwcode-kingsblogspotcomcom) ConsoleWriteLine(nPress any key to continue) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 19

Named ArgumentsParameters in C

Named Arguments are an alternative way for specifing 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 specifiying 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

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 divisor5)

int a = remainder(divisor5 dividend 10)

Note that the position of the arguments have been interchanged both the above methods will

produce the same output ie they would set the value of a as 0(which is the remainder when

dividing 10 by 5)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 20

Optional ArgumentsParameters in C

This article will show you what is meant by Optional ArgumentsParameters in C 50 Optional

Arguments are mostly necessary when you specify functions that have a large number of

arguments

Optional Arguments are purely optional ie even if you do not specify them its perfectly OK

But it doesnt 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

The values that we supply in the function Definition are some constants These are the values

that are to be used in case no value is supplied in the function call These values are specified by

typing in variable expressions instead of just the declaration of variables

For example we would write

static void Func(Str = Default Value)

instead of static void Func(int Str)

If you didnt 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

When using this technique it is best that you have declared optional amp required parameters both

ie 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 = NA)

In the example above Name amp Age are required parameters The string Address is optional if

not specified then it would take the value NA meaning that 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)

Please Note

Do not Copy amp Paste code written here instead type it in your Development

Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 21

Transpose a Matrix

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

details

using System using SystemText using SystemThreadingTasks 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] ConsoleWriteLine(Enter the number of rows and columns of matrix ) m = ConvertToInt16(ConsoleReadLine()) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(Enter the elements of matrix n) for (c = 0 c lt m c++) for (d = 0 d lt n d++) matrix[c d] = ConvertToInt16(ConsoleReadLine()) for (c = 0 c lt m c++) for (d = 0 d lt n d++) transpose[d c] = matrix[c d]

httpwwwcode-kingsblogspotcom Page 22

ConsoleWriteLine(Transpose of entered matrix) for (c = 0 c lt n c++) for (d = 0 d lt m d++) ConsoleWrite( + transpose[c d]) ConsoleWriteLine() ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 23

Fibonacci Series

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 amp 1 The series goes on like

this

01123581321345589144233377helliphellip

Here we illustrate two techniques for the creation of the Fibonacci Series to n terms The For

Loop method amp 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 amp Second) Then we calculate the next term by adding these two terms amp setting a

new set of two new terms These terms are the Second amp Newest

using System using SystemText using SystemThreadingTasks namespace Fibonacci_series_Using_For_Loop class Program static void Main(string[] args) int n first = 0 second = 1 next c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First + n + terms of Fibonacci series are) for (c = 0 c lt n c++) if (c lt= 1) next = c

httpwwwcode-kingsblogspotcom Page 24

else next = first + second first = second second = next ConsoleWriteLine(next) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 25

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 amp two less than the number supplied In this way final

output value has each number added twice excluding 0 amp 1 Check the program below

using System using SystemText using SystemThreadingTasks namespace Fibonacci_Series_Recursion class Program static void Main(string[] args) int n i = 0 c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First 5 terms of Fibonacci series are) for (c = 1 c lt= n c++) ConsoleWriteLine(Fibonacci(i)) i++ ConsoleReadKey() static int Fibonacci(int n) if (n == 0) return 0 else if (n == 1) return 1 else return (Fibonacci(n - 1) + Fibonacci(n - 2))

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 26

Get Date Difference in C

Getting differences in two given dates is as easy as it gets The function used here is the

End_DateSubtract(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

using System using SystemText namespace Print_and_Get_Date_Difference_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) ConsoleWriteLine(The Date Today Is) DateTime DT = new DateTime() DT = DateTimeTodayDate ConsoleWriteLine(DTDateToString()) ConsoleWriteLine(Calculate the difference between two datesn) int year month day ConsoleWriteLine(Enter Start Date) ConsoleWriteLine(Enter Year)

httpwwwcode-kingsblogspotcom Page 27

year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_Start = new DateTime(yearmonthday) ConsoleWriteLine(nEnter End Date) ConsoleWriteLine(Enter Year) year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_End = new DateTime(year month day) TimeSpan timespan = DT_EndSubtract(DT_Start) ConsoleWriteLine(nThe Difference isn) ConsoleWriteLine(timespanTotalDaysToString() + Daysn) ConsoleWriteLine((timespanTotalDays 365)ToString() + Years) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 28

Obtain Local Host IP in C

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 SystemNet

namespace Obtain_IP_Address_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) String StringHost if (argsLength == 0) Getting Ip address of local machine First get the host name of local machine StringHost = SystemNetDnsGetHostName() ConsoleWriteLine(Local Machine Host Name is + StringHost) ConsoleWriteLine() else StringHost = args[0]

httpwwwcode-kingsblogspotcom Page 29

Then using host name get the IP address list IPHostEntry ipEntry = SystemNetDnsGetHostEntry(StringHost) IPAddress[] address = ipEntryAddressList for (int i = 0 i lt addressLength i++) ConsoleWriteLine() ConsoleWriteLine(IP Address Type 0 1 i address[i]ToString()) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 30

Monitor Turn OnOffStandBy in C

You might want to change your display settings in a running program The code behind requires

the Import of a Dll amp execution of a function SendMessage() by supplying 4 parameters The

value of the fourth parameter having values 0 1 amp 2 has the monitor in the states ON STAND

BY amp 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 SystemWindowsForms using SystemRuntimeInteropServices namespace Turn_Off_Monitor public partial class Form1 Form public Form1() InitializeComponent() [DllImport(user32dll)] public static extern IntPtr SendMessage(IntPtr hWnd uint 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(thisHandle WM_SYSCOMMAND b a) private void btnMonitorOff_Click(object sender EventArgs e) IntPtr a = new IntPtr(2) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

httpwwwcode-kingsblogspotcom Page 31

private void btnMonitorOn_Click(object sender EventArgs e) IntPtr a = new IntPtr(-1) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 32

Search Techniques Linear amp Binary

Searching is needed when we have a large array of some data or objects amp 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 amp finds the

position of elements Below you will find two search techniques viz Linear Search amp Binary

Search implemented in C The code is simple amp easy to understand amp can be modified as per

need

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 33

Code for Linear Search Technique in C Sharp

using System

using SystemText

using SystemThreadingTasks

namespace Linear_Search

class Program

static void Main(string[] args)

Int16[] array = new Int16[100]

Int16 search c number

ConsoleWriteLine(Enter the number of elements in arrayn)

number = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + numberToString() + numbersn)

for (c = 0 c lt number c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter the number to searchn)

search = ConvertToInt16(ConsoleReadLine())

for (c = 0 c lt number c++)

if (array[c] == search) if required element found

ConsoleWriteLine(searchToString() + is at locn + (c + 1)ToString() + n)

break

if (c == number)

ConsoleWriteLine(searchToString() + is not present in arrayn)

ConsoleReadLine()

httpwwwcode-kingsblogspotcom Page 34

Code for Binary Search Technique in C Sharp

namespace Binary_Search

class Program

static void Main(string[] args)

int c first last middle n search

Int16[] array = new Int16[100]

ConsoleWriteLine(Enter number of elementsn)

n = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + nToString() + integersn)

for (c = 0 c lt n c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter value to findn)

search = ConvertToInt16(ConsoleReadLine())

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

while (first lt= last)

if (array[middle] lt search)

first = middle + 1

else if (array[middle] == search)

ConsoleWriteLine(search + found at location + (middle + 1))

break

else

last = middle - 1

middle = (first + last) 2

if (first gt last)

ConsoleWriteLine(Not found + search + is not present in the list)

httpwwwcode-kingsblogspotcom Page 35

Working With Strings The 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 amp 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 txtLengthText = textBoxTextLengthToString() trkBar1Maximum = textBoxTextLength private void trackBar1_Scroll(object sender EventArgs e) Set the Max Value of second TrackBar trkBar2Maximum = textBoxTextLength - trkBar1Value textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString()

httpwwwcode-kingsblogspotcom Page 36

txtTotCharsText = trkBar2ValueToString() textBoxSelect()

Let us understand the working of this property with a simple String ABCDEFGH Suppose

you wanted to select the characters from between B amp C and Between F amp 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 ie

include A as well in the selection

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 ie a reduced

Maximum value

private void trackBar2_Scroll(object sender EventArgs e) textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString() txtTotCharsText = trkBar2ValueToString()

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 16: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 16

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 TraceWriteLine() 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)

TraceWriteLine(message + message)

TraceWriteLine(member name + memberName)

TraceWriteLine(source file path + sourceFilePath)

TraceWriteLine(source line number + sourceLineNumber)

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

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 17

Reverse the Words in a Given 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 = strSourceSplit(new char[] ) string strReverse = stringEmpty for (int i = arySourceLength - 1 i gt= 0 i--) strReverse = strReverse + + arySource[i] ConsoleWriteLine(Original String nn + strSource) ConsoleWriteLine(nnReversed String nn + strReverse) return strReverse

httpwwwcode-kingsblogspotcom Page 18

static void Main(string[] args) reverseIt( I Am In Love With wwwcode-kingsblogspotcomcom) ConsoleWriteLine(nPress any key to continue) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 19

Named ArgumentsParameters in C

Named Arguments are an alternative way for specifing 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 specifiying 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

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 divisor5)

int a = remainder(divisor5 dividend 10)

Note that the position of the arguments have been interchanged both the above methods will

produce the same output ie they would set the value of a as 0(which is the remainder when

dividing 10 by 5)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 20

Optional ArgumentsParameters in C

This article will show you what is meant by Optional ArgumentsParameters in C 50 Optional

Arguments are mostly necessary when you specify functions that have a large number of

arguments

Optional Arguments are purely optional ie even if you do not specify them its perfectly OK

But it doesnt 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

The values that we supply in the function Definition are some constants These are the values

that are to be used in case no value is supplied in the function call These values are specified by

typing in variable expressions instead of just the declaration of variables

For example we would write

static void Func(Str = Default Value)

instead of static void Func(int Str)

If you didnt 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

When using this technique it is best that you have declared optional amp required parameters both

ie 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 = NA)

In the example above Name amp Age are required parameters The string Address is optional if

not specified then it would take the value NA meaning that 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)

Please Note

Do not Copy amp Paste code written here instead type it in your Development

Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 21

Transpose a Matrix

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

details

using System using SystemText using SystemThreadingTasks 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] ConsoleWriteLine(Enter the number of rows and columns of matrix ) m = ConvertToInt16(ConsoleReadLine()) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(Enter the elements of matrix n) for (c = 0 c lt m c++) for (d = 0 d lt n d++) matrix[c d] = ConvertToInt16(ConsoleReadLine()) for (c = 0 c lt m c++) for (d = 0 d lt n d++) transpose[d c] = matrix[c d]

httpwwwcode-kingsblogspotcom Page 22

ConsoleWriteLine(Transpose of entered matrix) for (c = 0 c lt n c++) for (d = 0 d lt m d++) ConsoleWrite( + transpose[c d]) ConsoleWriteLine() ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 23

Fibonacci Series

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 amp 1 The series goes on like

this

01123581321345589144233377helliphellip

Here we illustrate two techniques for the creation of the Fibonacci Series to n terms The For

Loop method amp 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 amp Second) Then we calculate the next term by adding these two terms amp setting a

new set of two new terms These terms are the Second amp Newest

using System using SystemText using SystemThreadingTasks namespace Fibonacci_series_Using_For_Loop class Program static void Main(string[] args) int n first = 0 second = 1 next c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First + n + terms of Fibonacci series are) for (c = 0 c lt n c++) if (c lt= 1) next = c

httpwwwcode-kingsblogspotcom Page 24

else next = first + second first = second second = next ConsoleWriteLine(next) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 25

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 amp two less than the number supplied In this way final

output value has each number added twice excluding 0 amp 1 Check the program below

using System using SystemText using SystemThreadingTasks namespace Fibonacci_Series_Recursion class Program static void Main(string[] args) int n i = 0 c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First 5 terms of Fibonacci series are) for (c = 1 c lt= n c++) ConsoleWriteLine(Fibonacci(i)) i++ ConsoleReadKey() static int Fibonacci(int n) if (n == 0) return 0 else if (n == 1) return 1 else return (Fibonacci(n - 1) + Fibonacci(n - 2))

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 26

Get Date Difference in C

Getting differences in two given dates is as easy as it gets The function used here is the

End_DateSubtract(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

using System using SystemText namespace Print_and_Get_Date_Difference_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) ConsoleWriteLine(The Date Today Is) DateTime DT = new DateTime() DT = DateTimeTodayDate ConsoleWriteLine(DTDateToString()) ConsoleWriteLine(Calculate the difference between two datesn) int year month day ConsoleWriteLine(Enter Start Date) ConsoleWriteLine(Enter Year)

httpwwwcode-kingsblogspotcom Page 27

year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_Start = new DateTime(yearmonthday) ConsoleWriteLine(nEnter End Date) ConsoleWriteLine(Enter Year) year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_End = new DateTime(year month day) TimeSpan timespan = DT_EndSubtract(DT_Start) ConsoleWriteLine(nThe Difference isn) ConsoleWriteLine(timespanTotalDaysToString() + Daysn) ConsoleWriteLine((timespanTotalDays 365)ToString() + Years) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 28

Obtain Local Host IP in C

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 SystemNet

namespace Obtain_IP_Address_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) String StringHost if (argsLength == 0) Getting Ip address of local machine First get the host name of local machine StringHost = SystemNetDnsGetHostName() ConsoleWriteLine(Local Machine Host Name is + StringHost) ConsoleWriteLine() else StringHost = args[0]

httpwwwcode-kingsblogspotcom Page 29

Then using host name get the IP address list IPHostEntry ipEntry = SystemNetDnsGetHostEntry(StringHost) IPAddress[] address = ipEntryAddressList for (int i = 0 i lt addressLength i++) ConsoleWriteLine() ConsoleWriteLine(IP Address Type 0 1 i address[i]ToString()) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 30

Monitor Turn OnOffStandBy in C

You might want to change your display settings in a running program The code behind requires

the Import of a Dll amp execution of a function SendMessage() by supplying 4 parameters The

value of the fourth parameter having values 0 1 amp 2 has the monitor in the states ON STAND

BY amp 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 SystemWindowsForms using SystemRuntimeInteropServices namespace Turn_Off_Monitor public partial class Form1 Form public Form1() InitializeComponent() [DllImport(user32dll)] public static extern IntPtr SendMessage(IntPtr hWnd uint 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(thisHandle WM_SYSCOMMAND b a) private void btnMonitorOff_Click(object sender EventArgs e) IntPtr a = new IntPtr(2) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

httpwwwcode-kingsblogspotcom Page 31

private void btnMonitorOn_Click(object sender EventArgs e) IntPtr a = new IntPtr(-1) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 32

Search Techniques Linear amp Binary

Searching is needed when we have a large array of some data or objects amp 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 amp finds the

position of elements Below you will find two search techniques viz Linear Search amp Binary

Search implemented in C The code is simple amp easy to understand amp can be modified as per

need

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 33

Code for Linear Search Technique in C Sharp

using System

using SystemText

using SystemThreadingTasks

namespace Linear_Search

class Program

static void Main(string[] args)

Int16[] array = new Int16[100]

Int16 search c number

ConsoleWriteLine(Enter the number of elements in arrayn)

number = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + numberToString() + numbersn)

for (c = 0 c lt number c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter the number to searchn)

search = ConvertToInt16(ConsoleReadLine())

for (c = 0 c lt number c++)

if (array[c] == search) if required element found

ConsoleWriteLine(searchToString() + is at locn + (c + 1)ToString() + n)

break

if (c == number)

ConsoleWriteLine(searchToString() + is not present in arrayn)

ConsoleReadLine()

httpwwwcode-kingsblogspotcom Page 34

Code for Binary Search Technique in C Sharp

namespace Binary_Search

class Program

static void Main(string[] args)

int c first last middle n search

Int16[] array = new Int16[100]

ConsoleWriteLine(Enter number of elementsn)

n = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + nToString() + integersn)

for (c = 0 c lt n c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter value to findn)

search = ConvertToInt16(ConsoleReadLine())

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

while (first lt= last)

if (array[middle] lt search)

first = middle + 1

else if (array[middle] == search)

ConsoleWriteLine(search + found at location + (middle + 1))

break

else

last = middle - 1

middle = (first + last) 2

if (first gt last)

ConsoleWriteLine(Not found + search + is not present in the list)

httpwwwcode-kingsblogspotcom Page 35

Working With Strings The 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 amp 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 txtLengthText = textBoxTextLengthToString() trkBar1Maximum = textBoxTextLength private void trackBar1_Scroll(object sender EventArgs e) Set the Max Value of second TrackBar trkBar2Maximum = textBoxTextLength - trkBar1Value textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString()

httpwwwcode-kingsblogspotcom Page 36

txtTotCharsText = trkBar2ValueToString() textBoxSelect()

Let us understand the working of this property with a simple String ABCDEFGH Suppose

you wanted to select the characters from between B amp C and Between F amp 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 ie

include A as well in the selection

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 ie a reduced

Maximum value

private void trackBar2_Scroll(object sender EventArgs e) textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString() txtTotCharsText = trkBar2ValueToString()

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 17: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 17

Reverse the Words in a Given 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 = strSourceSplit(new char[] ) string strReverse = stringEmpty for (int i = arySourceLength - 1 i gt= 0 i--) strReverse = strReverse + + arySource[i] ConsoleWriteLine(Original String nn + strSource) ConsoleWriteLine(nnReversed String nn + strReverse) return strReverse

httpwwwcode-kingsblogspotcom Page 18

static void Main(string[] args) reverseIt( I Am In Love With wwwcode-kingsblogspotcomcom) ConsoleWriteLine(nPress any key to continue) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 19

Named ArgumentsParameters in C

Named Arguments are an alternative way for specifing 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 specifiying 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

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 divisor5)

int a = remainder(divisor5 dividend 10)

Note that the position of the arguments have been interchanged both the above methods will

produce the same output ie they would set the value of a as 0(which is the remainder when

dividing 10 by 5)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 20

Optional ArgumentsParameters in C

This article will show you what is meant by Optional ArgumentsParameters in C 50 Optional

Arguments are mostly necessary when you specify functions that have a large number of

arguments

Optional Arguments are purely optional ie even if you do not specify them its perfectly OK

But it doesnt 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

The values that we supply in the function Definition are some constants These are the values

that are to be used in case no value is supplied in the function call These values are specified by

typing in variable expressions instead of just the declaration of variables

For example we would write

static void Func(Str = Default Value)

instead of static void Func(int Str)

If you didnt 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

When using this technique it is best that you have declared optional amp required parameters both

ie 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 = NA)

In the example above Name amp Age are required parameters The string Address is optional if

not specified then it would take the value NA meaning that 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)

Please Note

Do not Copy amp Paste code written here instead type it in your Development

Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 21

Transpose a Matrix

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

details

using System using SystemText using SystemThreadingTasks 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] ConsoleWriteLine(Enter the number of rows and columns of matrix ) m = ConvertToInt16(ConsoleReadLine()) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(Enter the elements of matrix n) for (c = 0 c lt m c++) for (d = 0 d lt n d++) matrix[c d] = ConvertToInt16(ConsoleReadLine()) for (c = 0 c lt m c++) for (d = 0 d lt n d++) transpose[d c] = matrix[c d]

httpwwwcode-kingsblogspotcom Page 22

ConsoleWriteLine(Transpose of entered matrix) for (c = 0 c lt n c++) for (d = 0 d lt m d++) ConsoleWrite( + transpose[c d]) ConsoleWriteLine() ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 23

Fibonacci Series

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 amp 1 The series goes on like

this

01123581321345589144233377helliphellip

Here we illustrate two techniques for the creation of the Fibonacci Series to n terms The For

Loop method amp 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 amp Second) Then we calculate the next term by adding these two terms amp setting a

new set of two new terms These terms are the Second amp Newest

using System using SystemText using SystemThreadingTasks namespace Fibonacci_series_Using_For_Loop class Program static void Main(string[] args) int n first = 0 second = 1 next c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First + n + terms of Fibonacci series are) for (c = 0 c lt n c++) if (c lt= 1) next = c

httpwwwcode-kingsblogspotcom Page 24

else next = first + second first = second second = next ConsoleWriteLine(next) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 25

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 amp two less than the number supplied In this way final

output value has each number added twice excluding 0 amp 1 Check the program below

using System using SystemText using SystemThreadingTasks namespace Fibonacci_Series_Recursion class Program static void Main(string[] args) int n i = 0 c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First 5 terms of Fibonacci series are) for (c = 1 c lt= n c++) ConsoleWriteLine(Fibonacci(i)) i++ ConsoleReadKey() static int Fibonacci(int n) if (n == 0) return 0 else if (n == 1) return 1 else return (Fibonacci(n - 1) + Fibonacci(n - 2))

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 26

Get Date Difference in C

Getting differences in two given dates is as easy as it gets The function used here is the

End_DateSubtract(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

using System using SystemText namespace Print_and_Get_Date_Difference_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) ConsoleWriteLine(The Date Today Is) DateTime DT = new DateTime() DT = DateTimeTodayDate ConsoleWriteLine(DTDateToString()) ConsoleWriteLine(Calculate the difference between two datesn) int year month day ConsoleWriteLine(Enter Start Date) ConsoleWriteLine(Enter Year)

httpwwwcode-kingsblogspotcom Page 27

year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_Start = new DateTime(yearmonthday) ConsoleWriteLine(nEnter End Date) ConsoleWriteLine(Enter Year) year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_End = new DateTime(year month day) TimeSpan timespan = DT_EndSubtract(DT_Start) ConsoleWriteLine(nThe Difference isn) ConsoleWriteLine(timespanTotalDaysToString() + Daysn) ConsoleWriteLine((timespanTotalDays 365)ToString() + Years) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 28

Obtain Local Host IP in C

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 SystemNet

namespace Obtain_IP_Address_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) String StringHost if (argsLength == 0) Getting Ip address of local machine First get the host name of local machine StringHost = SystemNetDnsGetHostName() ConsoleWriteLine(Local Machine Host Name is + StringHost) ConsoleWriteLine() else StringHost = args[0]

httpwwwcode-kingsblogspotcom Page 29

Then using host name get the IP address list IPHostEntry ipEntry = SystemNetDnsGetHostEntry(StringHost) IPAddress[] address = ipEntryAddressList for (int i = 0 i lt addressLength i++) ConsoleWriteLine() ConsoleWriteLine(IP Address Type 0 1 i address[i]ToString()) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 30

Monitor Turn OnOffStandBy in C

You might want to change your display settings in a running program The code behind requires

the Import of a Dll amp execution of a function SendMessage() by supplying 4 parameters The

value of the fourth parameter having values 0 1 amp 2 has the monitor in the states ON STAND

BY amp 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 SystemWindowsForms using SystemRuntimeInteropServices namespace Turn_Off_Monitor public partial class Form1 Form public Form1() InitializeComponent() [DllImport(user32dll)] public static extern IntPtr SendMessage(IntPtr hWnd uint 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(thisHandle WM_SYSCOMMAND b a) private void btnMonitorOff_Click(object sender EventArgs e) IntPtr a = new IntPtr(2) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

httpwwwcode-kingsblogspotcom Page 31

private void btnMonitorOn_Click(object sender EventArgs e) IntPtr a = new IntPtr(-1) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 32

Search Techniques Linear amp Binary

Searching is needed when we have a large array of some data or objects amp 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 amp finds the

position of elements Below you will find two search techniques viz Linear Search amp Binary

Search implemented in C The code is simple amp easy to understand amp can be modified as per

need

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 33

Code for Linear Search Technique in C Sharp

using System

using SystemText

using SystemThreadingTasks

namespace Linear_Search

class Program

static void Main(string[] args)

Int16[] array = new Int16[100]

Int16 search c number

ConsoleWriteLine(Enter the number of elements in arrayn)

number = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + numberToString() + numbersn)

for (c = 0 c lt number c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter the number to searchn)

search = ConvertToInt16(ConsoleReadLine())

for (c = 0 c lt number c++)

if (array[c] == search) if required element found

ConsoleWriteLine(searchToString() + is at locn + (c + 1)ToString() + n)

break

if (c == number)

ConsoleWriteLine(searchToString() + is not present in arrayn)

ConsoleReadLine()

httpwwwcode-kingsblogspotcom Page 34

Code for Binary Search Technique in C Sharp

namespace Binary_Search

class Program

static void Main(string[] args)

int c first last middle n search

Int16[] array = new Int16[100]

ConsoleWriteLine(Enter number of elementsn)

n = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + nToString() + integersn)

for (c = 0 c lt n c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter value to findn)

search = ConvertToInt16(ConsoleReadLine())

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

while (first lt= last)

if (array[middle] lt search)

first = middle + 1

else if (array[middle] == search)

ConsoleWriteLine(search + found at location + (middle + 1))

break

else

last = middle - 1

middle = (first + last) 2

if (first gt last)

ConsoleWriteLine(Not found + search + is not present in the list)

httpwwwcode-kingsblogspotcom Page 35

Working With Strings The 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 amp 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 txtLengthText = textBoxTextLengthToString() trkBar1Maximum = textBoxTextLength private void trackBar1_Scroll(object sender EventArgs e) Set the Max Value of second TrackBar trkBar2Maximum = textBoxTextLength - trkBar1Value textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString()

httpwwwcode-kingsblogspotcom Page 36

txtTotCharsText = trkBar2ValueToString() textBoxSelect()

Let us understand the working of this property with a simple String ABCDEFGH Suppose

you wanted to select the characters from between B amp C and Between F amp 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 ie

include A as well in the selection

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 ie a reduced

Maximum value

private void trackBar2_Scroll(object sender EventArgs e) textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString() txtTotCharsText = trkBar2ValueToString()

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 18: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 18

static void Main(string[] args) reverseIt( I Am In Love With wwwcode-kingsblogspotcomcom) ConsoleWriteLine(nPress any key to continue) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 19

Named ArgumentsParameters in C

Named Arguments are an alternative way for specifing 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 specifiying 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

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 divisor5)

int a = remainder(divisor5 dividend 10)

Note that the position of the arguments have been interchanged both the above methods will

produce the same output ie they would set the value of a as 0(which is the remainder when

dividing 10 by 5)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 20

Optional ArgumentsParameters in C

This article will show you what is meant by Optional ArgumentsParameters in C 50 Optional

Arguments are mostly necessary when you specify functions that have a large number of

arguments

Optional Arguments are purely optional ie even if you do not specify them its perfectly OK

But it doesnt 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

The values that we supply in the function Definition are some constants These are the values

that are to be used in case no value is supplied in the function call These values are specified by

typing in variable expressions instead of just the declaration of variables

For example we would write

static void Func(Str = Default Value)

instead of static void Func(int Str)

If you didnt 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

When using this technique it is best that you have declared optional amp required parameters both

ie 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 = NA)

In the example above Name amp Age are required parameters The string Address is optional if

not specified then it would take the value NA meaning that 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)

Please Note

Do not Copy amp Paste code written here instead type it in your Development

Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 21

Transpose a Matrix

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

details

using System using SystemText using SystemThreadingTasks 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] ConsoleWriteLine(Enter the number of rows and columns of matrix ) m = ConvertToInt16(ConsoleReadLine()) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(Enter the elements of matrix n) for (c = 0 c lt m c++) for (d = 0 d lt n d++) matrix[c d] = ConvertToInt16(ConsoleReadLine()) for (c = 0 c lt m c++) for (d = 0 d lt n d++) transpose[d c] = matrix[c d]

httpwwwcode-kingsblogspotcom Page 22

ConsoleWriteLine(Transpose of entered matrix) for (c = 0 c lt n c++) for (d = 0 d lt m d++) ConsoleWrite( + transpose[c d]) ConsoleWriteLine() ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 23

Fibonacci Series

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 amp 1 The series goes on like

this

01123581321345589144233377helliphellip

Here we illustrate two techniques for the creation of the Fibonacci Series to n terms The For

Loop method amp 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 amp Second) Then we calculate the next term by adding these two terms amp setting a

new set of two new terms These terms are the Second amp Newest

using System using SystemText using SystemThreadingTasks namespace Fibonacci_series_Using_For_Loop class Program static void Main(string[] args) int n first = 0 second = 1 next c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First + n + terms of Fibonacci series are) for (c = 0 c lt n c++) if (c lt= 1) next = c

httpwwwcode-kingsblogspotcom Page 24

else next = first + second first = second second = next ConsoleWriteLine(next) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 25

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 amp two less than the number supplied In this way final

output value has each number added twice excluding 0 amp 1 Check the program below

using System using SystemText using SystemThreadingTasks namespace Fibonacci_Series_Recursion class Program static void Main(string[] args) int n i = 0 c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First 5 terms of Fibonacci series are) for (c = 1 c lt= n c++) ConsoleWriteLine(Fibonacci(i)) i++ ConsoleReadKey() static int Fibonacci(int n) if (n == 0) return 0 else if (n == 1) return 1 else return (Fibonacci(n - 1) + Fibonacci(n - 2))

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 26

Get Date Difference in C

Getting differences in two given dates is as easy as it gets The function used here is the

End_DateSubtract(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

using System using SystemText namespace Print_and_Get_Date_Difference_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) ConsoleWriteLine(The Date Today Is) DateTime DT = new DateTime() DT = DateTimeTodayDate ConsoleWriteLine(DTDateToString()) ConsoleWriteLine(Calculate the difference between two datesn) int year month day ConsoleWriteLine(Enter Start Date) ConsoleWriteLine(Enter Year)

httpwwwcode-kingsblogspotcom Page 27

year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_Start = new DateTime(yearmonthday) ConsoleWriteLine(nEnter End Date) ConsoleWriteLine(Enter Year) year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_End = new DateTime(year month day) TimeSpan timespan = DT_EndSubtract(DT_Start) ConsoleWriteLine(nThe Difference isn) ConsoleWriteLine(timespanTotalDaysToString() + Daysn) ConsoleWriteLine((timespanTotalDays 365)ToString() + Years) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 28

Obtain Local Host IP in C

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 SystemNet

namespace Obtain_IP_Address_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) String StringHost if (argsLength == 0) Getting Ip address of local machine First get the host name of local machine StringHost = SystemNetDnsGetHostName() ConsoleWriteLine(Local Machine Host Name is + StringHost) ConsoleWriteLine() else StringHost = args[0]

httpwwwcode-kingsblogspotcom Page 29

Then using host name get the IP address list IPHostEntry ipEntry = SystemNetDnsGetHostEntry(StringHost) IPAddress[] address = ipEntryAddressList for (int i = 0 i lt addressLength i++) ConsoleWriteLine() ConsoleWriteLine(IP Address Type 0 1 i address[i]ToString()) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 30

Monitor Turn OnOffStandBy in C

You might want to change your display settings in a running program The code behind requires

the Import of a Dll amp execution of a function SendMessage() by supplying 4 parameters The

value of the fourth parameter having values 0 1 amp 2 has the monitor in the states ON STAND

BY amp 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 SystemWindowsForms using SystemRuntimeInteropServices namespace Turn_Off_Monitor public partial class Form1 Form public Form1() InitializeComponent() [DllImport(user32dll)] public static extern IntPtr SendMessage(IntPtr hWnd uint 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(thisHandle WM_SYSCOMMAND b a) private void btnMonitorOff_Click(object sender EventArgs e) IntPtr a = new IntPtr(2) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

httpwwwcode-kingsblogspotcom Page 31

private void btnMonitorOn_Click(object sender EventArgs e) IntPtr a = new IntPtr(-1) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 32

Search Techniques Linear amp Binary

Searching is needed when we have a large array of some data or objects amp 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 amp finds the

position of elements Below you will find two search techniques viz Linear Search amp Binary

Search implemented in C The code is simple amp easy to understand amp can be modified as per

need

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 33

Code for Linear Search Technique in C Sharp

using System

using SystemText

using SystemThreadingTasks

namespace Linear_Search

class Program

static void Main(string[] args)

Int16[] array = new Int16[100]

Int16 search c number

ConsoleWriteLine(Enter the number of elements in arrayn)

number = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + numberToString() + numbersn)

for (c = 0 c lt number c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter the number to searchn)

search = ConvertToInt16(ConsoleReadLine())

for (c = 0 c lt number c++)

if (array[c] == search) if required element found

ConsoleWriteLine(searchToString() + is at locn + (c + 1)ToString() + n)

break

if (c == number)

ConsoleWriteLine(searchToString() + is not present in arrayn)

ConsoleReadLine()

httpwwwcode-kingsblogspotcom Page 34

Code for Binary Search Technique in C Sharp

namespace Binary_Search

class Program

static void Main(string[] args)

int c first last middle n search

Int16[] array = new Int16[100]

ConsoleWriteLine(Enter number of elementsn)

n = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + nToString() + integersn)

for (c = 0 c lt n c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter value to findn)

search = ConvertToInt16(ConsoleReadLine())

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

while (first lt= last)

if (array[middle] lt search)

first = middle + 1

else if (array[middle] == search)

ConsoleWriteLine(search + found at location + (middle + 1))

break

else

last = middle - 1

middle = (first + last) 2

if (first gt last)

ConsoleWriteLine(Not found + search + is not present in the list)

httpwwwcode-kingsblogspotcom Page 35

Working With Strings The 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 amp 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 txtLengthText = textBoxTextLengthToString() trkBar1Maximum = textBoxTextLength private void trackBar1_Scroll(object sender EventArgs e) Set the Max Value of second TrackBar trkBar2Maximum = textBoxTextLength - trkBar1Value textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString()

httpwwwcode-kingsblogspotcom Page 36

txtTotCharsText = trkBar2ValueToString() textBoxSelect()

Let us understand the working of this property with a simple String ABCDEFGH Suppose

you wanted to select the characters from between B amp C and Between F amp 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 ie

include A as well in the selection

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 ie a reduced

Maximum value

private void trackBar2_Scroll(object sender EventArgs e) textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString() txtTotCharsText = trkBar2ValueToString()

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 19: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 19

Named ArgumentsParameters in C

Named Arguments are an alternative way for specifing 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 specifiying 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

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 divisor5)

int a = remainder(divisor5 dividend 10)

Note that the position of the arguments have been interchanged both the above methods will

produce the same output ie they would set the value of a as 0(which is the remainder when

dividing 10 by 5)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 20

Optional ArgumentsParameters in C

This article will show you what is meant by Optional ArgumentsParameters in C 50 Optional

Arguments are mostly necessary when you specify functions that have a large number of

arguments

Optional Arguments are purely optional ie even if you do not specify them its perfectly OK

But it doesnt 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

The values that we supply in the function Definition are some constants These are the values

that are to be used in case no value is supplied in the function call These values are specified by

typing in variable expressions instead of just the declaration of variables

For example we would write

static void Func(Str = Default Value)

instead of static void Func(int Str)

If you didnt 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

When using this technique it is best that you have declared optional amp required parameters both

ie 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 = NA)

In the example above Name amp Age are required parameters The string Address is optional if

not specified then it would take the value NA meaning that 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)

Please Note

Do not Copy amp Paste code written here instead type it in your Development

Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 21

Transpose a Matrix

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

details

using System using SystemText using SystemThreadingTasks 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] ConsoleWriteLine(Enter the number of rows and columns of matrix ) m = ConvertToInt16(ConsoleReadLine()) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(Enter the elements of matrix n) for (c = 0 c lt m c++) for (d = 0 d lt n d++) matrix[c d] = ConvertToInt16(ConsoleReadLine()) for (c = 0 c lt m c++) for (d = 0 d lt n d++) transpose[d c] = matrix[c d]

httpwwwcode-kingsblogspotcom Page 22

ConsoleWriteLine(Transpose of entered matrix) for (c = 0 c lt n c++) for (d = 0 d lt m d++) ConsoleWrite( + transpose[c d]) ConsoleWriteLine() ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 23

Fibonacci Series

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 amp 1 The series goes on like

this

01123581321345589144233377helliphellip

Here we illustrate two techniques for the creation of the Fibonacci Series to n terms The For

Loop method amp 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 amp Second) Then we calculate the next term by adding these two terms amp setting a

new set of two new terms These terms are the Second amp Newest

using System using SystemText using SystemThreadingTasks namespace Fibonacci_series_Using_For_Loop class Program static void Main(string[] args) int n first = 0 second = 1 next c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First + n + terms of Fibonacci series are) for (c = 0 c lt n c++) if (c lt= 1) next = c

httpwwwcode-kingsblogspotcom Page 24

else next = first + second first = second second = next ConsoleWriteLine(next) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 25

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 amp two less than the number supplied In this way final

output value has each number added twice excluding 0 amp 1 Check the program below

using System using SystemText using SystemThreadingTasks namespace Fibonacci_Series_Recursion class Program static void Main(string[] args) int n i = 0 c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First 5 terms of Fibonacci series are) for (c = 1 c lt= n c++) ConsoleWriteLine(Fibonacci(i)) i++ ConsoleReadKey() static int Fibonacci(int n) if (n == 0) return 0 else if (n == 1) return 1 else return (Fibonacci(n - 1) + Fibonacci(n - 2))

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 26

Get Date Difference in C

Getting differences in two given dates is as easy as it gets The function used here is the

End_DateSubtract(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

using System using SystemText namespace Print_and_Get_Date_Difference_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) ConsoleWriteLine(The Date Today Is) DateTime DT = new DateTime() DT = DateTimeTodayDate ConsoleWriteLine(DTDateToString()) ConsoleWriteLine(Calculate the difference between two datesn) int year month day ConsoleWriteLine(Enter Start Date) ConsoleWriteLine(Enter Year)

httpwwwcode-kingsblogspotcom Page 27

year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_Start = new DateTime(yearmonthday) ConsoleWriteLine(nEnter End Date) ConsoleWriteLine(Enter Year) year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_End = new DateTime(year month day) TimeSpan timespan = DT_EndSubtract(DT_Start) ConsoleWriteLine(nThe Difference isn) ConsoleWriteLine(timespanTotalDaysToString() + Daysn) ConsoleWriteLine((timespanTotalDays 365)ToString() + Years) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 28

Obtain Local Host IP in C

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 SystemNet

namespace Obtain_IP_Address_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) String StringHost if (argsLength == 0) Getting Ip address of local machine First get the host name of local machine StringHost = SystemNetDnsGetHostName() ConsoleWriteLine(Local Machine Host Name is + StringHost) ConsoleWriteLine() else StringHost = args[0]

httpwwwcode-kingsblogspotcom Page 29

Then using host name get the IP address list IPHostEntry ipEntry = SystemNetDnsGetHostEntry(StringHost) IPAddress[] address = ipEntryAddressList for (int i = 0 i lt addressLength i++) ConsoleWriteLine() ConsoleWriteLine(IP Address Type 0 1 i address[i]ToString()) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 30

Monitor Turn OnOffStandBy in C

You might want to change your display settings in a running program The code behind requires

the Import of a Dll amp execution of a function SendMessage() by supplying 4 parameters The

value of the fourth parameter having values 0 1 amp 2 has the monitor in the states ON STAND

BY amp 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 SystemWindowsForms using SystemRuntimeInteropServices namespace Turn_Off_Monitor public partial class Form1 Form public Form1() InitializeComponent() [DllImport(user32dll)] public static extern IntPtr SendMessage(IntPtr hWnd uint 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(thisHandle WM_SYSCOMMAND b a) private void btnMonitorOff_Click(object sender EventArgs e) IntPtr a = new IntPtr(2) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

httpwwwcode-kingsblogspotcom Page 31

private void btnMonitorOn_Click(object sender EventArgs e) IntPtr a = new IntPtr(-1) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 32

Search Techniques Linear amp Binary

Searching is needed when we have a large array of some data or objects amp 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 amp finds the

position of elements Below you will find two search techniques viz Linear Search amp Binary

Search implemented in C The code is simple amp easy to understand amp can be modified as per

need

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 33

Code for Linear Search Technique in C Sharp

using System

using SystemText

using SystemThreadingTasks

namespace Linear_Search

class Program

static void Main(string[] args)

Int16[] array = new Int16[100]

Int16 search c number

ConsoleWriteLine(Enter the number of elements in arrayn)

number = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + numberToString() + numbersn)

for (c = 0 c lt number c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter the number to searchn)

search = ConvertToInt16(ConsoleReadLine())

for (c = 0 c lt number c++)

if (array[c] == search) if required element found

ConsoleWriteLine(searchToString() + is at locn + (c + 1)ToString() + n)

break

if (c == number)

ConsoleWriteLine(searchToString() + is not present in arrayn)

ConsoleReadLine()

httpwwwcode-kingsblogspotcom Page 34

Code for Binary Search Technique in C Sharp

namespace Binary_Search

class Program

static void Main(string[] args)

int c first last middle n search

Int16[] array = new Int16[100]

ConsoleWriteLine(Enter number of elementsn)

n = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + nToString() + integersn)

for (c = 0 c lt n c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter value to findn)

search = ConvertToInt16(ConsoleReadLine())

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

while (first lt= last)

if (array[middle] lt search)

first = middle + 1

else if (array[middle] == search)

ConsoleWriteLine(search + found at location + (middle + 1))

break

else

last = middle - 1

middle = (first + last) 2

if (first gt last)

ConsoleWriteLine(Not found + search + is not present in the list)

httpwwwcode-kingsblogspotcom Page 35

Working With Strings The 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 amp 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 txtLengthText = textBoxTextLengthToString() trkBar1Maximum = textBoxTextLength private void trackBar1_Scroll(object sender EventArgs e) Set the Max Value of second TrackBar trkBar2Maximum = textBoxTextLength - trkBar1Value textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString()

httpwwwcode-kingsblogspotcom Page 36

txtTotCharsText = trkBar2ValueToString() textBoxSelect()

Let us understand the working of this property with a simple String ABCDEFGH Suppose

you wanted to select the characters from between B amp C and Between F amp 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 ie

include A as well in the selection

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 ie a reduced

Maximum value

private void trackBar2_Scroll(object sender EventArgs e) textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString() txtTotCharsText = trkBar2ValueToString()

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 20: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 20

Optional ArgumentsParameters in C

This article will show you what is meant by Optional ArgumentsParameters in C 50 Optional

Arguments are mostly necessary when you specify functions that have a large number of

arguments

Optional Arguments are purely optional ie even if you do not specify them its perfectly OK

But it doesnt 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

The values that we supply in the function Definition are some constants These are the values

that are to be used in case no value is supplied in the function call These values are specified by

typing in variable expressions instead of just the declaration of variables

For example we would write

static void Func(Str = Default Value)

instead of static void Func(int Str)

If you didnt 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

When using this technique it is best that you have declared optional amp required parameters both

ie 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 = NA)

In the example above Name amp Age are required parameters The string Address is optional if

not specified then it would take the value NA meaning that 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)

Please Note

Do not Copy amp Paste code written here instead type it in your Development

Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 21

Transpose a Matrix

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

details

using System using SystemText using SystemThreadingTasks 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] ConsoleWriteLine(Enter the number of rows and columns of matrix ) m = ConvertToInt16(ConsoleReadLine()) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(Enter the elements of matrix n) for (c = 0 c lt m c++) for (d = 0 d lt n d++) matrix[c d] = ConvertToInt16(ConsoleReadLine()) for (c = 0 c lt m c++) for (d = 0 d lt n d++) transpose[d c] = matrix[c d]

httpwwwcode-kingsblogspotcom Page 22

ConsoleWriteLine(Transpose of entered matrix) for (c = 0 c lt n c++) for (d = 0 d lt m d++) ConsoleWrite( + transpose[c d]) ConsoleWriteLine() ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 23

Fibonacci Series

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 amp 1 The series goes on like

this

01123581321345589144233377helliphellip

Here we illustrate two techniques for the creation of the Fibonacci Series to n terms The For

Loop method amp 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 amp Second) Then we calculate the next term by adding these two terms amp setting a

new set of two new terms These terms are the Second amp Newest

using System using SystemText using SystemThreadingTasks namespace Fibonacci_series_Using_For_Loop class Program static void Main(string[] args) int n first = 0 second = 1 next c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First + n + terms of Fibonacci series are) for (c = 0 c lt n c++) if (c lt= 1) next = c

httpwwwcode-kingsblogspotcom Page 24

else next = first + second first = second second = next ConsoleWriteLine(next) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 25

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 amp two less than the number supplied In this way final

output value has each number added twice excluding 0 amp 1 Check the program below

using System using SystemText using SystemThreadingTasks namespace Fibonacci_Series_Recursion class Program static void Main(string[] args) int n i = 0 c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First 5 terms of Fibonacci series are) for (c = 1 c lt= n c++) ConsoleWriteLine(Fibonacci(i)) i++ ConsoleReadKey() static int Fibonacci(int n) if (n == 0) return 0 else if (n == 1) return 1 else return (Fibonacci(n - 1) + Fibonacci(n - 2))

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 26

Get Date Difference in C

Getting differences in two given dates is as easy as it gets The function used here is the

End_DateSubtract(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

using System using SystemText namespace Print_and_Get_Date_Difference_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) ConsoleWriteLine(The Date Today Is) DateTime DT = new DateTime() DT = DateTimeTodayDate ConsoleWriteLine(DTDateToString()) ConsoleWriteLine(Calculate the difference between two datesn) int year month day ConsoleWriteLine(Enter Start Date) ConsoleWriteLine(Enter Year)

httpwwwcode-kingsblogspotcom Page 27

year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_Start = new DateTime(yearmonthday) ConsoleWriteLine(nEnter End Date) ConsoleWriteLine(Enter Year) year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_End = new DateTime(year month day) TimeSpan timespan = DT_EndSubtract(DT_Start) ConsoleWriteLine(nThe Difference isn) ConsoleWriteLine(timespanTotalDaysToString() + Daysn) ConsoleWriteLine((timespanTotalDays 365)ToString() + Years) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 28

Obtain Local Host IP in C

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 SystemNet

namespace Obtain_IP_Address_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) String StringHost if (argsLength == 0) Getting Ip address of local machine First get the host name of local machine StringHost = SystemNetDnsGetHostName() ConsoleWriteLine(Local Machine Host Name is + StringHost) ConsoleWriteLine() else StringHost = args[0]

httpwwwcode-kingsblogspotcom Page 29

Then using host name get the IP address list IPHostEntry ipEntry = SystemNetDnsGetHostEntry(StringHost) IPAddress[] address = ipEntryAddressList for (int i = 0 i lt addressLength i++) ConsoleWriteLine() ConsoleWriteLine(IP Address Type 0 1 i address[i]ToString()) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 30

Monitor Turn OnOffStandBy in C

You might want to change your display settings in a running program The code behind requires

the Import of a Dll amp execution of a function SendMessage() by supplying 4 parameters The

value of the fourth parameter having values 0 1 amp 2 has the monitor in the states ON STAND

BY amp 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 SystemWindowsForms using SystemRuntimeInteropServices namespace Turn_Off_Monitor public partial class Form1 Form public Form1() InitializeComponent() [DllImport(user32dll)] public static extern IntPtr SendMessage(IntPtr hWnd uint 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(thisHandle WM_SYSCOMMAND b a) private void btnMonitorOff_Click(object sender EventArgs e) IntPtr a = new IntPtr(2) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

httpwwwcode-kingsblogspotcom Page 31

private void btnMonitorOn_Click(object sender EventArgs e) IntPtr a = new IntPtr(-1) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 32

Search Techniques Linear amp Binary

Searching is needed when we have a large array of some data or objects amp 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 amp finds the

position of elements Below you will find two search techniques viz Linear Search amp Binary

Search implemented in C The code is simple amp easy to understand amp can be modified as per

need

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 33

Code for Linear Search Technique in C Sharp

using System

using SystemText

using SystemThreadingTasks

namespace Linear_Search

class Program

static void Main(string[] args)

Int16[] array = new Int16[100]

Int16 search c number

ConsoleWriteLine(Enter the number of elements in arrayn)

number = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + numberToString() + numbersn)

for (c = 0 c lt number c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter the number to searchn)

search = ConvertToInt16(ConsoleReadLine())

for (c = 0 c lt number c++)

if (array[c] == search) if required element found

ConsoleWriteLine(searchToString() + is at locn + (c + 1)ToString() + n)

break

if (c == number)

ConsoleWriteLine(searchToString() + is not present in arrayn)

ConsoleReadLine()

httpwwwcode-kingsblogspotcom Page 34

Code for Binary Search Technique in C Sharp

namespace Binary_Search

class Program

static void Main(string[] args)

int c first last middle n search

Int16[] array = new Int16[100]

ConsoleWriteLine(Enter number of elementsn)

n = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + nToString() + integersn)

for (c = 0 c lt n c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter value to findn)

search = ConvertToInt16(ConsoleReadLine())

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

while (first lt= last)

if (array[middle] lt search)

first = middle + 1

else if (array[middle] == search)

ConsoleWriteLine(search + found at location + (middle + 1))

break

else

last = middle - 1

middle = (first + last) 2

if (first gt last)

ConsoleWriteLine(Not found + search + is not present in the list)

httpwwwcode-kingsblogspotcom Page 35

Working With Strings The 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 amp 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 txtLengthText = textBoxTextLengthToString() trkBar1Maximum = textBoxTextLength private void trackBar1_Scroll(object sender EventArgs e) Set the Max Value of second TrackBar trkBar2Maximum = textBoxTextLength - trkBar1Value textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString()

httpwwwcode-kingsblogspotcom Page 36

txtTotCharsText = trkBar2ValueToString() textBoxSelect()

Let us understand the working of this property with a simple String ABCDEFGH Suppose

you wanted to select the characters from between B amp C and Between F amp 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 ie

include A as well in the selection

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 ie a reduced

Maximum value

private void trackBar2_Scroll(object sender EventArgs e) textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString() txtTotCharsText = trkBar2ValueToString()

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 21: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 21

Transpose a Matrix

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

details

using System using SystemText using SystemThreadingTasks 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] ConsoleWriteLine(Enter the number of rows and columns of matrix ) m = ConvertToInt16(ConsoleReadLine()) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(Enter the elements of matrix n) for (c = 0 c lt m c++) for (d = 0 d lt n d++) matrix[c d] = ConvertToInt16(ConsoleReadLine()) for (c = 0 c lt m c++) for (d = 0 d lt n d++) transpose[d c] = matrix[c d]

httpwwwcode-kingsblogspotcom Page 22

ConsoleWriteLine(Transpose of entered matrix) for (c = 0 c lt n c++) for (d = 0 d lt m d++) ConsoleWrite( + transpose[c d]) ConsoleWriteLine() ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 23

Fibonacci Series

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 amp 1 The series goes on like

this

01123581321345589144233377helliphellip

Here we illustrate two techniques for the creation of the Fibonacci Series to n terms The For

Loop method amp 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 amp Second) Then we calculate the next term by adding these two terms amp setting a

new set of two new terms These terms are the Second amp Newest

using System using SystemText using SystemThreadingTasks namespace Fibonacci_series_Using_For_Loop class Program static void Main(string[] args) int n first = 0 second = 1 next c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First + n + terms of Fibonacci series are) for (c = 0 c lt n c++) if (c lt= 1) next = c

httpwwwcode-kingsblogspotcom Page 24

else next = first + second first = second second = next ConsoleWriteLine(next) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 25

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 amp two less than the number supplied In this way final

output value has each number added twice excluding 0 amp 1 Check the program below

using System using SystemText using SystemThreadingTasks namespace Fibonacci_Series_Recursion class Program static void Main(string[] args) int n i = 0 c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First 5 terms of Fibonacci series are) for (c = 1 c lt= n c++) ConsoleWriteLine(Fibonacci(i)) i++ ConsoleReadKey() static int Fibonacci(int n) if (n == 0) return 0 else if (n == 1) return 1 else return (Fibonacci(n - 1) + Fibonacci(n - 2))

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 26

Get Date Difference in C

Getting differences in two given dates is as easy as it gets The function used here is the

End_DateSubtract(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

using System using SystemText namespace Print_and_Get_Date_Difference_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) ConsoleWriteLine(The Date Today Is) DateTime DT = new DateTime() DT = DateTimeTodayDate ConsoleWriteLine(DTDateToString()) ConsoleWriteLine(Calculate the difference between two datesn) int year month day ConsoleWriteLine(Enter Start Date) ConsoleWriteLine(Enter Year)

httpwwwcode-kingsblogspotcom Page 27

year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_Start = new DateTime(yearmonthday) ConsoleWriteLine(nEnter End Date) ConsoleWriteLine(Enter Year) year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_End = new DateTime(year month day) TimeSpan timespan = DT_EndSubtract(DT_Start) ConsoleWriteLine(nThe Difference isn) ConsoleWriteLine(timespanTotalDaysToString() + Daysn) ConsoleWriteLine((timespanTotalDays 365)ToString() + Years) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 28

Obtain Local Host IP in C

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 SystemNet

namespace Obtain_IP_Address_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) String StringHost if (argsLength == 0) Getting Ip address of local machine First get the host name of local machine StringHost = SystemNetDnsGetHostName() ConsoleWriteLine(Local Machine Host Name is + StringHost) ConsoleWriteLine() else StringHost = args[0]

httpwwwcode-kingsblogspotcom Page 29

Then using host name get the IP address list IPHostEntry ipEntry = SystemNetDnsGetHostEntry(StringHost) IPAddress[] address = ipEntryAddressList for (int i = 0 i lt addressLength i++) ConsoleWriteLine() ConsoleWriteLine(IP Address Type 0 1 i address[i]ToString()) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 30

Monitor Turn OnOffStandBy in C

You might want to change your display settings in a running program The code behind requires

the Import of a Dll amp execution of a function SendMessage() by supplying 4 parameters The

value of the fourth parameter having values 0 1 amp 2 has the monitor in the states ON STAND

BY amp 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 SystemWindowsForms using SystemRuntimeInteropServices namespace Turn_Off_Monitor public partial class Form1 Form public Form1() InitializeComponent() [DllImport(user32dll)] public static extern IntPtr SendMessage(IntPtr hWnd uint 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(thisHandle WM_SYSCOMMAND b a) private void btnMonitorOff_Click(object sender EventArgs e) IntPtr a = new IntPtr(2) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

httpwwwcode-kingsblogspotcom Page 31

private void btnMonitorOn_Click(object sender EventArgs e) IntPtr a = new IntPtr(-1) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 32

Search Techniques Linear amp Binary

Searching is needed when we have a large array of some data or objects amp 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 amp finds the

position of elements Below you will find two search techniques viz Linear Search amp Binary

Search implemented in C The code is simple amp easy to understand amp can be modified as per

need

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 33

Code for Linear Search Technique in C Sharp

using System

using SystemText

using SystemThreadingTasks

namespace Linear_Search

class Program

static void Main(string[] args)

Int16[] array = new Int16[100]

Int16 search c number

ConsoleWriteLine(Enter the number of elements in arrayn)

number = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + numberToString() + numbersn)

for (c = 0 c lt number c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter the number to searchn)

search = ConvertToInt16(ConsoleReadLine())

for (c = 0 c lt number c++)

if (array[c] == search) if required element found

ConsoleWriteLine(searchToString() + is at locn + (c + 1)ToString() + n)

break

if (c == number)

ConsoleWriteLine(searchToString() + is not present in arrayn)

ConsoleReadLine()

httpwwwcode-kingsblogspotcom Page 34

Code for Binary Search Technique in C Sharp

namespace Binary_Search

class Program

static void Main(string[] args)

int c first last middle n search

Int16[] array = new Int16[100]

ConsoleWriteLine(Enter number of elementsn)

n = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + nToString() + integersn)

for (c = 0 c lt n c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter value to findn)

search = ConvertToInt16(ConsoleReadLine())

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

while (first lt= last)

if (array[middle] lt search)

first = middle + 1

else if (array[middle] == search)

ConsoleWriteLine(search + found at location + (middle + 1))

break

else

last = middle - 1

middle = (first + last) 2

if (first gt last)

ConsoleWriteLine(Not found + search + is not present in the list)

httpwwwcode-kingsblogspotcom Page 35

Working With Strings The 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 amp 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 txtLengthText = textBoxTextLengthToString() trkBar1Maximum = textBoxTextLength private void trackBar1_Scroll(object sender EventArgs e) Set the Max Value of second TrackBar trkBar2Maximum = textBoxTextLength - trkBar1Value textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString()

httpwwwcode-kingsblogspotcom Page 36

txtTotCharsText = trkBar2ValueToString() textBoxSelect()

Let us understand the working of this property with a simple String ABCDEFGH Suppose

you wanted to select the characters from between B amp C and Between F amp 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 ie

include A as well in the selection

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 ie a reduced

Maximum value

private void trackBar2_Scroll(object sender EventArgs e) textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString() txtTotCharsText = trkBar2ValueToString()

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 22: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 22

ConsoleWriteLine(Transpose of entered matrix) for (c = 0 c lt n c++) for (d = 0 d lt m d++) ConsoleWrite( + transpose[c d]) ConsoleWriteLine() ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 23

Fibonacci Series

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 amp 1 The series goes on like

this

01123581321345589144233377helliphellip

Here we illustrate two techniques for the creation of the Fibonacci Series to n terms The For

Loop method amp 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 amp Second) Then we calculate the next term by adding these two terms amp setting a

new set of two new terms These terms are the Second amp Newest

using System using SystemText using SystemThreadingTasks namespace Fibonacci_series_Using_For_Loop class Program static void Main(string[] args) int n first = 0 second = 1 next c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First + n + terms of Fibonacci series are) for (c = 0 c lt n c++) if (c lt= 1) next = c

httpwwwcode-kingsblogspotcom Page 24

else next = first + second first = second second = next ConsoleWriteLine(next) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 25

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 amp two less than the number supplied In this way final

output value has each number added twice excluding 0 amp 1 Check the program below

using System using SystemText using SystemThreadingTasks namespace Fibonacci_Series_Recursion class Program static void Main(string[] args) int n i = 0 c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First 5 terms of Fibonacci series are) for (c = 1 c lt= n c++) ConsoleWriteLine(Fibonacci(i)) i++ ConsoleReadKey() static int Fibonacci(int n) if (n == 0) return 0 else if (n == 1) return 1 else return (Fibonacci(n - 1) + Fibonacci(n - 2))

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 26

Get Date Difference in C

Getting differences in two given dates is as easy as it gets The function used here is the

End_DateSubtract(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

using System using SystemText namespace Print_and_Get_Date_Difference_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) ConsoleWriteLine(The Date Today Is) DateTime DT = new DateTime() DT = DateTimeTodayDate ConsoleWriteLine(DTDateToString()) ConsoleWriteLine(Calculate the difference between two datesn) int year month day ConsoleWriteLine(Enter Start Date) ConsoleWriteLine(Enter Year)

httpwwwcode-kingsblogspotcom Page 27

year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_Start = new DateTime(yearmonthday) ConsoleWriteLine(nEnter End Date) ConsoleWriteLine(Enter Year) year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_End = new DateTime(year month day) TimeSpan timespan = DT_EndSubtract(DT_Start) ConsoleWriteLine(nThe Difference isn) ConsoleWriteLine(timespanTotalDaysToString() + Daysn) ConsoleWriteLine((timespanTotalDays 365)ToString() + Years) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 28

Obtain Local Host IP in C

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 SystemNet

namespace Obtain_IP_Address_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) String StringHost if (argsLength == 0) Getting Ip address of local machine First get the host name of local machine StringHost = SystemNetDnsGetHostName() ConsoleWriteLine(Local Machine Host Name is + StringHost) ConsoleWriteLine() else StringHost = args[0]

httpwwwcode-kingsblogspotcom Page 29

Then using host name get the IP address list IPHostEntry ipEntry = SystemNetDnsGetHostEntry(StringHost) IPAddress[] address = ipEntryAddressList for (int i = 0 i lt addressLength i++) ConsoleWriteLine() ConsoleWriteLine(IP Address Type 0 1 i address[i]ToString()) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 30

Monitor Turn OnOffStandBy in C

You might want to change your display settings in a running program The code behind requires

the Import of a Dll amp execution of a function SendMessage() by supplying 4 parameters The

value of the fourth parameter having values 0 1 amp 2 has the monitor in the states ON STAND

BY amp 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 SystemWindowsForms using SystemRuntimeInteropServices namespace Turn_Off_Monitor public partial class Form1 Form public Form1() InitializeComponent() [DllImport(user32dll)] public static extern IntPtr SendMessage(IntPtr hWnd uint 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(thisHandle WM_SYSCOMMAND b a) private void btnMonitorOff_Click(object sender EventArgs e) IntPtr a = new IntPtr(2) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

httpwwwcode-kingsblogspotcom Page 31

private void btnMonitorOn_Click(object sender EventArgs e) IntPtr a = new IntPtr(-1) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 32

Search Techniques Linear amp Binary

Searching is needed when we have a large array of some data or objects amp 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 amp finds the

position of elements Below you will find two search techniques viz Linear Search amp Binary

Search implemented in C The code is simple amp easy to understand amp can be modified as per

need

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 33

Code for Linear Search Technique in C Sharp

using System

using SystemText

using SystemThreadingTasks

namespace Linear_Search

class Program

static void Main(string[] args)

Int16[] array = new Int16[100]

Int16 search c number

ConsoleWriteLine(Enter the number of elements in arrayn)

number = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + numberToString() + numbersn)

for (c = 0 c lt number c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter the number to searchn)

search = ConvertToInt16(ConsoleReadLine())

for (c = 0 c lt number c++)

if (array[c] == search) if required element found

ConsoleWriteLine(searchToString() + is at locn + (c + 1)ToString() + n)

break

if (c == number)

ConsoleWriteLine(searchToString() + is not present in arrayn)

ConsoleReadLine()

httpwwwcode-kingsblogspotcom Page 34

Code for Binary Search Technique in C Sharp

namespace Binary_Search

class Program

static void Main(string[] args)

int c first last middle n search

Int16[] array = new Int16[100]

ConsoleWriteLine(Enter number of elementsn)

n = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + nToString() + integersn)

for (c = 0 c lt n c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter value to findn)

search = ConvertToInt16(ConsoleReadLine())

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

while (first lt= last)

if (array[middle] lt search)

first = middle + 1

else if (array[middle] == search)

ConsoleWriteLine(search + found at location + (middle + 1))

break

else

last = middle - 1

middle = (first + last) 2

if (first gt last)

ConsoleWriteLine(Not found + search + is not present in the list)

httpwwwcode-kingsblogspotcom Page 35

Working With Strings The 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 amp 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 txtLengthText = textBoxTextLengthToString() trkBar1Maximum = textBoxTextLength private void trackBar1_Scroll(object sender EventArgs e) Set the Max Value of second TrackBar trkBar2Maximum = textBoxTextLength - trkBar1Value textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString()

httpwwwcode-kingsblogspotcom Page 36

txtTotCharsText = trkBar2ValueToString() textBoxSelect()

Let us understand the working of this property with a simple String ABCDEFGH Suppose

you wanted to select the characters from between B amp C and Between F amp 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 ie

include A as well in the selection

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 ie a reduced

Maximum value

private void trackBar2_Scroll(object sender EventArgs e) textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString() txtTotCharsText = trkBar2ValueToString()

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 23: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 23

Fibonacci Series

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 amp 1 The series goes on like

this

01123581321345589144233377helliphellip

Here we illustrate two techniques for the creation of the Fibonacci Series to n terms The For

Loop method amp 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 amp Second) Then we calculate the next term by adding these two terms amp setting a

new set of two new terms These terms are the Second amp Newest

using System using SystemText using SystemThreadingTasks namespace Fibonacci_series_Using_For_Loop class Program static void Main(string[] args) int n first = 0 second = 1 next c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First + n + terms of Fibonacci series are) for (c = 0 c lt n c++) if (c lt= 1) next = c

httpwwwcode-kingsblogspotcom Page 24

else next = first + second first = second second = next ConsoleWriteLine(next) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 25

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 amp two less than the number supplied In this way final

output value has each number added twice excluding 0 amp 1 Check the program below

using System using SystemText using SystemThreadingTasks namespace Fibonacci_Series_Recursion class Program static void Main(string[] args) int n i = 0 c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First 5 terms of Fibonacci series are) for (c = 1 c lt= n c++) ConsoleWriteLine(Fibonacci(i)) i++ ConsoleReadKey() static int Fibonacci(int n) if (n == 0) return 0 else if (n == 1) return 1 else return (Fibonacci(n - 1) + Fibonacci(n - 2))

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 26

Get Date Difference in C

Getting differences in two given dates is as easy as it gets The function used here is the

End_DateSubtract(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

using System using SystemText namespace Print_and_Get_Date_Difference_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) ConsoleWriteLine(The Date Today Is) DateTime DT = new DateTime() DT = DateTimeTodayDate ConsoleWriteLine(DTDateToString()) ConsoleWriteLine(Calculate the difference between two datesn) int year month day ConsoleWriteLine(Enter Start Date) ConsoleWriteLine(Enter Year)

httpwwwcode-kingsblogspotcom Page 27

year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_Start = new DateTime(yearmonthday) ConsoleWriteLine(nEnter End Date) ConsoleWriteLine(Enter Year) year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_End = new DateTime(year month day) TimeSpan timespan = DT_EndSubtract(DT_Start) ConsoleWriteLine(nThe Difference isn) ConsoleWriteLine(timespanTotalDaysToString() + Daysn) ConsoleWriteLine((timespanTotalDays 365)ToString() + Years) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 28

Obtain Local Host IP in C

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 SystemNet

namespace Obtain_IP_Address_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) String StringHost if (argsLength == 0) Getting Ip address of local machine First get the host name of local machine StringHost = SystemNetDnsGetHostName() ConsoleWriteLine(Local Machine Host Name is + StringHost) ConsoleWriteLine() else StringHost = args[0]

httpwwwcode-kingsblogspotcom Page 29

Then using host name get the IP address list IPHostEntry ipEntry = SystemNetDnsGetHostEntry(StringHost) IPAddress[] address = ipEntryAddressList for (int i = 0 i lt addressLength i++) ConsoleWriteLine() ConsoleWriteLine(IP Address Type 0 1 i address[i]ToString()) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 30

Monitor Turn OnOffStandBy in C

You might want to change your display settings in a running program The code behind requires

the Import of a Dll amp execution of a function SendMessage() by supplying 4 parameters The

value of the fourth parameter having values 0 1 amp 2 has the monitor in the states ON STAND

BY amp 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 SystemWindowsForms using SystemRuntimeInteropServices namespace Turn_Off_Monitor public partial class Form1 Form public Form1() InitializeComponent() [DllImport(user32dll)] public static extern IntPtr SendMessage(IntPtr hWnd uint 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(thisHandle WM_SYSCOMMAND b a) private void btnMonitorOff_Click(object sender EventArgs e) IntPtr a = new IntPtr(2) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

httpwwwcode-kingsblogspotcom Page 31

private void btnMonitorOn_Click(object sender EventArgs e) IntPtr a = new IntPtr(-1) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 32

Search Techniques Linear amp Binary

Searching is needed when we have a large array of some data or objects amp 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 amp finds the

position of elements Below you will find two search techniques viz Linear Search amp Binary

Search implemented in C The code is simple amp easy to understand amp can be modified as per

need

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 33

Code for Linear Search Technique in C Sharp

using System

using SystemText

using SystemThreadingTasks

namespace Linear_Search

class Program

static void Main(string[] args)

Int16[] array = new Int16[100]

Int16 search c number

ConsoleWriteLine(Enter the number of elements in arrayn)

number = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + numberToString() + numbersn)

for (c = 0 c lt number c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter the number to searchn)

search = ConvertToInt16(ConsoleReadLine())

for (c = 0 c lt number c++)

if (array[c] == search) if required element found

ConsoleWriteLine(searchToString() + is at locn + (c + 1)ToString() + n)

break

if (c == number)

ConsoleWriteLine(searchToString() + is not present in arrayn)

ConsoleReadLine()

httpwwwcode-kingsblogspotcom Page 34

Code for Binary Search Technique in C Sharp

namespace Binary_Search

class Program

static void Main(string[] args)

int c first last middle n search

Int16[] array = new Int16[100]

ConsoleWriteLine(Enter number of elementsn)

n = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + nToString() + integersn)

for (c = 0 c lt n c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter value to findn)

search = ConvertToInt16(ConsoleReadLine())

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

while (first lt= last)

if (array[middle] lt search)

first = middle + 1

else if (array[middle] == search)

ConsoleWriteLine(search + found at location + (middle + 1))

break

else

last = middle - 1

middle = (first + last) 2

if (first gt last)

ConsoleWriteLine(Not found + search + is not present in the list)

httpwwwcode-kingsblogspotcom Page 35

Working With Strings The 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 amp 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 txtLengthText = textBoxTextLengthToString() trkBar1Maximum = textBoxTextLength private void trackBar1_Scroll(object sender EventArgs e) Set the Max Value of second TrackBar trkBar2Maximum = textBoxTextLength - trkBar1Value textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString()

httpwwwcode-kingsblogspotcom Page 36

txtTotCharsText = trkBar2ValueToString() textBoxSelect()

Let us understand the working of this property with a simple String ABCDEFGH Suppose

you wanted to select the characters from between B amp C and Between F amp 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 ie

include A as well in the selection

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 ie a reduced

Maximum value

private void trackBar2_Scroll(object sender EventArgs e) textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString() txtTotCharsText = trkBar2ValueToString()

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 24: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 24

else next = first + second first = second second = next ConsoleWriteLine(next) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 25

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 amp two less than the number supplied In this way final

output value has each number added twice excluding 0 amp 1 Check the program below

using System using SystemText using SystemThreadingTasks namespace Fibonacci_Series_Recursion class Program static void Main(string[] args) int n i = 0 c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First 5 terms of Fibonacci series are) for (c = 1 c lt= n c++) ConsoleWriteLine(Fibonacci(i)) i++ ConsoleReadKey() static int Fibonacci(int n) if (n == 0) return 0 else if (n == 1) return 1 else return (Fibonacci(n - 1) + Fibonacci(n - 2))

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 26

Get Date Difference in C

Getting differences in two given dates is as easy as it gets The function used here is the

End_DateSubtract(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

using System using SystemText namespace Print_and_Get_Date_Difference_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) ConsoleWriteLine(The Date Today Is) DateTime DT = new DateTime() DT = DateTimeTodayDate ConsoleWriteLine(DTDateToString()) ConsoleWriteLine(Calculate the difference between two datesn) int year month day ConsoleWriteLine(Enter Start Date) ConsoleWriteLine(Enter Year)

httpwwwcode-kingsblogspotcom Page 27

year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_Start = new DateTime(yearmonthday) ConsoleWriteLine(nEnter End Date) ConsoleWriteLine(Enter Year) year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_End = new DateTime(year month day) TimeSpan timespan = DT_EndSubtract(DT_Start) ConsoleWriteLine(nThe Difference isn) ConsoleWriteLine(timespanTotalDaysToString() + Daysn) ConsoleWriteLine((timespanTotalDays 365)ToString() + Years) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 28

Obtain Local Host IP in C

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 SystemNet

namespace Obtain_IP_Address_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) String StringHost if (argsLength == 0) Getting Ip address of local machine First get the host name of local machine StringHost = SystemNetDnsGetHostName() ConsoleWriteLine(Local Machine Host Name is + StringHost) ConsoleWriteLine() else StringHost = args[0]

httpwwwcode-kingsblogspotcom Page 29

Then using host name get the IP address list IPHostEntry ipEntry = SystemNetDnsGetHostEntry(StringHost) IPAddress[] address = ipEntryAddressList for (int i = 0 i lt addressLength i++) ConsoleWriteLine() ConsoleWriteLine(IP Address Type 0 1 i address[i]ToString()) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 30

Monitor Turn OnOffStandBy in C

You might want to change your display settings in a running program The code behind requires

the Import of a Dll amp execution of a function SendMessage() by supplying 4 parameters The

value of the fourth parameter having values 0 1 amp 2 has the monitor in the states ON STAND

BY amp 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 SystemWindowsForms using SystemRuntimeInteropServices namespace Turn_Off_Monitor public partial class Form1 Form public Form1() InitializeComponent() [DllImport(user32dll)] public static extern IntPtr SendMessage(IntPtr hWnd uint 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(thisHandle WM_SYSCOMMAND b a) private void btnMonitorOff_Click(object sender EventArgs e) IntPtr a = new IntPtr(2) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

httpwwwcode-kingsblogspotcom Page 31

private void btnMonitorOn_Click(object sender EventArgs e) IntPtr a = new IntPtr(-1) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 32

Search Techniques Linear amp Binary

Searching is needed when we have a large array of some data or objects amp 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 amp finds the

position of elements Below you will find two search techniques viz Linear Search amp Binary

Search implemented in C The code is simple amp easy to understand amp can be modified as per

need

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 33

Code for Linear Search Technique in C Sharp

using System

using SystemText

using SystemThreadingTasks

namespace Linear_Search

class Program

static void Main(string[] args)

Int16[] array = new Int16[100]

Int16 search c number

ConsoleWriteLine(Enter the number of elements in arrayn)

number = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + numberToString() + numbersn)

for (c = 0 c lt number c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter the number to searchn)

search = ConvertToInt16(ConsoleReadLine())

for (c = 0 c lt number c++)

if (array[c] == search) if required element found

ConsoleWriteLine(searchToString() + is at locn + (c + 1)ToString() + n)

break

if (c == number)

ConsoleWriteLine(searchToString() + is not present in arrayn)

ConsoleReadLine()

httpwwwcode-kingsblogspotcom Page 34

Code for Binary Search Technique in C Sharp

namespace Binary_Search

class Program

static void Main(string[] args)

int c first last middle n search

Int16[] array = new Int16[100]

ConsoleWriteLine(Enter number of elementsn)

n = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + nToString() + integersn)

for (c = 0 c lt n c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter value to findn)

search = ConvertToInt16(ConsoleReadLine())

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

while (first lt= last)

if (array[middle] lt search)

first = middle + 1

else if (array[middle] == search)

ConsoleWriteLine(search + found at location + (middle + 1))

break

else

last = middle - 1

middle = (first + last) 2

if (first gt last)

ConsoleWriteLine(Not found + search + is not present in the list)

httpwwwcode-kingsblogspotcom Page 35

Working With Strings The 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 amp 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 txtLengthText = textBoxTextLengthToString() trkBar1Maximum = textBoxTextLength private void trackBar1_Scroll(object sender EventArgs e) Set the Max Value of second TrackBar trkBar2Maximum = textBoxTextLength - trkBar1Value textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString()

httpwwwcode-kingsblogspotcom Page 36

txtTotCharsText = trkBar2ValueToString() textBoxSelect()

Let us understand the working of this property with a simple String ABCDEFGH Suppose

you wanted to select the characters from between B amp C and Between F amp 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 ie

include A as well in the selection

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 ie a reduced

Maximum value

private void trackBar2_Scroll(object sender EventArgs e) textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString() txtTotCharsText = trkBar2ValueToString()

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 25: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 25

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 amp two less than the number supplied In this way final

output value has each number added twice excluding 0 amp 1 Check the program below

using System using SystemText using SystemThreadingTasks namespace Fibonacci_Series_Recursion class Program static void Main(string[] args) int n i = 0 c ConsoleWriteLine(Enter the number of terms) n = ConvertToInt16(ConsoleReadLine()) ConsoleWriteLine(First 5 terms of Fibonacci series are) for (c = 1 c lt= n c++) ConsoleWriteLine(Fibonacci(i)) i++ ConsoleReadKey() static int Fibonacci(int n) if (n == 0) return 0 else if (n == 1) return 1 else return (Fibonacci(n - 1) + Fibonacci(n - 2))

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 26

Get Date Difference in C

Getting differences in two given dates is as easy as it gets The function used here is the

End_DateSubtract(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

using System using SystemText namespace Print_and_Get_Date_Difference_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) ConsoleWriteLine(The Date Today Is) DateTime DT = new DateTime() DT = DateTimeTodayDate ConsoleWriteLine(DTDateToString()) ConsoleWriteLine(Calculate the difference between two datesn) int year month day ConsoleWriteLine(Enter Start Date) ConsoleWriteLine(Enter Year)

httpwwwcode-kingsblogspotcom Page 27

year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_Start = new DateTime(yearmonthday) ConsoleWriteLine(nEnter End Date) ConsoleWriteLine(Enter Year) year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_End = new DateTime(year month day) TimeSpan timespan = DT_EndSubtract(DT_Start) ConsoleWriteLine(nThe Difference isn) ConsoleWriteLine(timespanTotalDaysToString() + Daysn) ConsoleWriteLine((timespanTotalDays 365)ToString() + Years) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 28

Obtain Local Host IP in C

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 SystemNet

namespace Obtain_IP_Address_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) String StringHost if (argsLength == 0) Getting Ip address of local machine First get the host name of local machine StringHost = SystemNetDnsGetHostName() ConsoleWriteLine(Local Machine Host Name is + StringHost) ConsoleWriteLine() else StringHost = args[0]

httpwwwcode-kingsblogspotcom Page 29

Then using host name get the IP address list IPHostEntry ipEntry = SystemNetDnsGetHostEntry(StringHost) IPAddress[] address = ipEntryAddressList for (int i = 0 i lt addressLength i++) ConsoleWriteLine() ConsoleWriteLine(IP Address Type 0 1 i address[i]ToString()) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 30

Monitor Turn OnOffStandBy in C

You might want to change your display settings in a running program The code behind requires

the Import of a Dll amp execution of a function SendMessage() by supplying 4 parameters The

value of the fourth parameter having values 0 1 amp 2 has the monitor in the states ON STAND

BY amp 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 SystemWindowsForms using SystemRuntimeInteropServices namespace Turn_Off_Monitor public partial class Form1 Form public Form1() InitializeComponent() [DllImport(user32dll)] public static extern IntPtr SendMessage(IntPtr hWnd uint 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(thisHandle WM_SYSCOMMAND b a) private void btnMonitorOff_Click(object sender EventArgs e) IntPtr a = new IntPtr(2) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

httpwwwcode-kingsblogspotcom Page 31

private void btnMonitorOn_Click(object sender EventArgs e) IntPtr a = new IntPtr(-1) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 32

Search Techniques Linear amp Binary

Searching is needed when we have a large array of some data or objects amp 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 amp finds the

position of elements Below you will find two search techniques viz Linear Search amp Binary

Search implemented in C The code is simple amp easy to understand amp can be modified as per

need

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 33

Code for Linear Search Technique in C Sharp

using System

using SystemText

using SystemThreadingTasks

namespace Linear_Search

class Program

static void Main(string[] args)

Int16[] array = new Int16[100]

Int16 search c number

ConsoleWriteLine(Enter the number of elements in arrayn)

number = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + numberToString() + numbersn)

for (c = 0 c lt number c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter the number to searchn)

search = ConvertToInt16(ConsoleReadLine())

for (c = 0 c lt number c++)

if (array[c] == search) if required element found

ConsoleWriteLine(searchToString() + is at locn + (c + 1)ToString() + n)

break

if (c == number)

ConsoleWriteLine(searchToString() + is not present in arrayn)

ConsoleReadLine()

httpwwwcode-kingsblogspotcom Page 34

Code for Binary Search Technique in C Sharp

namespace Binary_Search

class Program

static void Main(string[] args)

int c first last middle n search

Int16[] array = new Int16[100]

ConsoleWriteLine(Enter number of elementsn)

n = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + nToString() + integersn)

for (c = 0 c lt n c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter value to findn)

search = ConvertToInt16(ConsoleReadLine())

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

while (first lt= last)

if (array[middle] lt search)

first = middle + 1

else if (array[middle] == search)

ConsoleWriteLine(search + found at location + (middle + 1))

break

else

last = middle - 1

middle = (first + last) 2

if (first gt last)

ConsoleWriteLine(Not found + search + is not present in the list)

httpwwwcode-kingsblogspotcom Page 35

Working With Strings The 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 amp 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 txtLengthText = textBoxTextLengthToString() trkBar1Maximum = textBoxTextLength private void trackBar1_Scroll(object sender EventArgs e) Set the Max Value of second TrackBar trkBar2Maximum = textBoxTextLength - trkBar1Value textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString()

httpwwwcode-kingsblogspotcom Page 36

txtTotCharsText = trkBar2ValueToString() textBoxSelect()

Let us understand the working of this property with a simple String ABCDEFGH Suppose

you wanted to select the characters from between B amp C and Between F amp 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 ie

include A as well in the selection

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 ie a reduced

Maximum value

private void trackBar2_Scroll(object sender EventArgs e) textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString() txtTotCharsText = trkBar2ValueToString()

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 26: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 26

Get Date Difference in C

Getting differences in two given dates is as easy as it gets The function used here is the

End_DateSubtract(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

using System using SystemText namespace Print_and_Get_Date_Difference_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) ConsoleWriteLine(The Date Today Is) DateTime DT = new DateTime() DT = DateTimeTodayDate ConsoleWriteLine(DTDateToString()) ConsoleWriteLine(Calculate the difference between two datesn) int year month day ConsoleWriteLine(Enter Start Date) ConsoleWriteLine(Enter Year)

httpwwwcode-kingsblogspotcom Page 27

year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_Start = new DateTime(yearmonthday) ConsoleWriteLine(nEnter End Date) ConsoleWriteLine(Enter Year) year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_End = new DateTime(year month day) TimeSpan timespan = DT_EndSubtract(DT_Start) ConsoleWriteLine(nThe Difference isn) ConsoleWriteLine(timespanTotalDaysToString() + Daysn) ConsoleWriteLine((timespanTotalDays 365)ToString() + Years) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 28

Obtain Local Host IP in C

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 SystemNet

namespace Obtain_IP_Address_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) String StringHost if (argsLength == 0) Getting Ip address of local machine First get the host name of local machine StringHost = SystemNetDnsGetHostName() ConsoleWriteLine(Local Machine Host Name is + StringHost) ConsoleWriteLine() else StringHost = args[0]

httpwwwcode-kingsblogspotcom Page 29

Then using host name get the IP address list IPHostEntry ipEntry = SystemNetDnsGetHostEntry(StringHost) IPAddress[] address = ipEntryAddressList for (int i = 0 i lt addressLength i++) ConsoleWriteLine() ConsoleWriteLine(IP Address Type 0 1 i address[i]ToString()) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 30

Monitor Turn OnOffStandBy in C

You might want to change your display settings in a running program The code behind requires

the Import of a Dll amp execution of a function SendMessage() by supplying 4 parameters The

value of the fourth parameter having values 0 1 amp 2 has the monitor in the states ON STAND

BY amp 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 SystemWindowsForms using SystemRuntimeInteropServices namespace Turn_Off_Monitor public partial class Form1 Form public Form1() InitializeComponent() [DllImport(user32dll)] public static extern IntPtr SendMessage(IntPtr hWnd uint 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(thisHandle WM_SYSCOMMAND b a) private void btnMonitorOff_Click(object sender EventArgs e) IntPtr a = new IntPtr(2) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

httpwwwcode-kingsblogspotcom Page 31

private void btnMonitorOn_Click(object sender EventArgs e) IntPtr a = new IntPtr(-1) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 32

Search Techniques Linear amp Binary

Searching is needed when we have a large array of some data or objects amp 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 amp finds the

position of elements Below you will find two search techniques viz Linear Search amp Binary

Search implemented in C The code is simple amp easy to understand amp can be modified as per

need

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 33

Code for Linear Search Technique in C Sharp

using System

using SystemText

using SystemThreadingTasks

namespace Linear_Search

class Program

static void Main(string[] args)

Int16[] array = new Int16[100]

Int16 search c number

ConsoleWriteLine(Enter the number of elements in arrayn)

number = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + numberToString() + numbersn)

for (c = 0 c lt number c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter the number to searchn)

search = ConvertToInt16(ConsoleReadLine())

for (c = 0 c lt number c++)

if (array[c] == search) if required element found

ConsoleWriteLine(searchToString() + is at locn + (c + 1)ToString() + n)

break

if (c == number)

ConsoleWriteLine(searchToString() + is not present in arrayn)

ConsoleReadLine()

httpwwwcode-kingsblogspotcom Page 34

Code for Binary Search Technique in C Sharp

namespace Binary_Search

class Program

static void Main(string[] args)

int c first last middle n search

Int16[] array = new Int16[100]

ConsoleWriteLine(Enter number of elementsn)

n = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + nToString() + integersn)

for (c = 0 c lt n c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter value to findn)

search = ConvertToInt16(ConsoleReadLine())

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

while (first lt= last)

if (array[middle] lt search)

first = middle + 1

else if (array[middle] == search)

ConsoleWriteLine(search + found at location + (middle + 1))

break

else

last = middle - 1

middle = (first + last) 2

if (first gt last)

ConsoleWriteLine(Not found + search + is not present in the list)

httpwwwcode-kingsblogspotcom Page 35

Working With Strings The 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 amp 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 txtLengthText = textBoxTextLengthToString() trkBar1Maximum = textBoxTextLength private void trackBar1_Scroll(object sender EventArgs e) Set the Max Value of second TrackBar trkBar2Maximum = textBoxTextLength - trkBar1Value textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString()

httpwwwcode-kingsblogspotcom Page 36

txtTotCharsText = trkBar2ValueToString() textBoxSelect()

Let us understand the working of this property with a simple String ABCDEFGH Suppose

you wanted to select the characters from between B amp C and Between F amp 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 ie

include A as well in the selection

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 ie a reduced

Maximum value

private void trackBar2_Scroll(object sender EventArgs e) textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString() txtTotCharsText = trkBar2ValueToString()

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 27: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 27

year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_Start = new DateTime(yearmonthday) ConsoleWriteLine(nEnter End Date) ConsoleWriteLine(Enter Year) year = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Month) month = ConvertToInt16(ConsoleReadLine()ToString()) ConsoleWriteLine(Enter Day) day = ConvertToInt16(ConsoleReadLine()ToString()) DateTime DT_End = new DateTime(year month day) TimeSpan timespan = DT_EndSubtract(DT_Start) ConsoleWriteLine(nThe Difference isn) ConsoleWriteLine(timespanTotalDaysToString() + Daysn) ConsoleWriteLine((timespanTotalDays 365)ToString() + Years) ConsoleReadKey()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 28

Obtain Local Host IP in C

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 SystemNet

namespace Obtain_IP_Address_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) String StringHost if (argsLength == 0) Getting Ip address of local machine First get the host name of local machine StringHost = SystemNetDnsGetHostName() ConsoleWriteLine(Local Machine Host Name is + StringHost) ConsoleWriteLine() else StringHost = args[0]

httpwwwcode-kingsblogspotcom Page 29

Then using host name get the IP address list IPHostEntry ipEntry = SystemNetDnsGetHostEntry(StringHost) IPAddress[] address = ipEntryAddressList for (int i = 0 i lt addressLength i++) ConsoleWriteLine() ConsoleWriteLine(IP Address Type 0 1 i address[i]ToString()) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 30

Monitor Turn OnOffStandBy in C

You might want to change your display settings in a running program The code behind requires

the Import of a Dll amp execution of a function SendMessage() by supplying 4 parameters The

value of the fourth parameter having values 0 1 amp 2 has the monitor in the states ON STAND

BY amp 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 SystemWindowsForms using SystemRuntimeInteropServices namespace Turn_Off_Monitor public partial class Form1 Form public Form1() InitializeComponent() [DllImport(user32dll)] public static extern IntPtr SendMessage(IntPtr hWnd uint 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(thisHandle WM_SYSCOMMAND b a) private void btnMonitorOff_Click(object sender EventArgs e) IntPtr a = new IntPtr(2) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

httpwwwcode-kingsblogspotcom Page 31

private void btnMonitorOn_Click(object sender EventArgs e) IntPtr a = new IntPtr(-1) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 32

Search Techniques Linear amp Binary

Searching is needed when we have a large array of some data or objects amp 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 amp finds the

position of elements Below you will find two search techniques viz Linear Search amp Binary

Search implemented in C The code is simple amp easy to understand amp can be modified as per

need

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 33

Code for Linear Search Technique in C Sharp

using System

using SystemText

using SystemThreadingTasks

namespace Linear_Search

class Program

static void Main(string[] args)

Int16[] array = new Int16[100]

Int16 search c number

ConsoleWriteLine(Enter the number of elements in arrayn)

number = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + numberToString() + numbersn)

for (c = 0 c lt number c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter the number to searchn)

search = ConvertToInt16(ConsoleReadLine())

for (c = 0 c lt number c++)

if (array[c] == search) if required element found

ConsoleWriteLine(searchToString() + is at locn + (c + 1)ToString() + n)

break

if (c == number)

ConsoleWriteLine(searchToString() + is not present in arrayn)

ConsoleReadLine()

httpwwwcode-kingsblogspotcom Page 34

Code for Binary Search Technique in C Sharp

namespace Binary_Search

class Program

static void Main(string[] args)

int c first last middle n search

Int16[] array = new Int16[100]

ConsoleWriteLine(Enter number of elementsn)

n = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + nToString() + integersn)

for (c = 0 c lt n c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter value to findn)

search = ConvertToInt16(ConsoleReadLine())

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

while (first lt= last)

if (array[middle] lt search)

first = middle + 1

else if (array[middle] == search)

ConsoleWriteLine(search + found at location + (middle + 1))

break

else

last = middle - 1

middle = (first + last) 2

if (first gt last)

ConsoleWriteLine(Not found + search + is not present in the list)

httpwwwcode-kingsblogspotcom Page 35

Working With Strings The 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 amp 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 txtLengthText = textBoxTextLengthToString() trkBar1Maximum = textBoxTextLength private void trackBar1_Scroll(object sender EventArgs e) Set the Max Value of second TrackBar trkBar2Maximum = textBoxTextLength - trkBar1Value textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString()

httpwwwcode-kingsblogspotcom Page 36

txtTotCharsText = trkBar2ValueToString() textBoxSelect()

Let us understand the working of this property with a simple String ABCDEFGH Suppose

you wanted to select the characters from between B amp C and Between F amp 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 ie

include A as well in the selection

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 ie a reduced

Maximum value

private void trackBar2_Scroll(object sender EventArgs e) textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString() txtTotCharsText = trkBar2ValueToString()

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 28: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 28

Obtain Local Host IP in C

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 SystemNet

namespace Obtain_IP_Address_in_C_Sharp class Program static void Main(string[] args) ConsoleWriteLine() ConsoleWriteLine(wwwcode-kingsblogspotcom) ConsoleWriteLine(n) String StringHost if (argsLength == 0) Getting Ip address of local machine First get the host name of local machine StringHost = SystemNetDnsGetHostName() ConsoleWriteLine(Local Machine Host Name is + StringHost) ConsoleWriteLine() else StringHost = args[0]

httpwwwcode-kingsblogspotcom Page 29

Then using host name get the IP address list IPHostEntry ipEntry = SystemNetDnsGetHostEntry(StringHost) IPAddress[] address = ipEntryAddressList for (int i = 0 i lt addressLength i++) ConsoleWriteLine() ConsoleWriteLine(IP Address Type 0 1 i address[i]ToString()) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 30

Monitor Turn OnOffStandBy in C

You might want to change your display settings in a running program The code behind requires

the Import of a Dll amp execution of a function SendMessage() by supplying 4 parameters The

value of the fourth parameter having values 0 1 amp 2 has the monitor in the states ON STAND

BY amp 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 SystemWindowsForms using SystemRuntimeInteropServices namespace Turn_Off_Monitor public partial class Form1 Form public Form1() InitializeComponent() [DllImport(user32dll)] public static extern IntPtr SendMessage(IntPtr hWnd uint 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(thisHandle WM_SYSCOMMAND b a) private void btnMonitorOff_Click(object sender EventArgs e) IntPtr a = new IntPtr(2) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

httpwwwcode-kingsblogspotcom Page 31

private void btnMonitorOn_Click(object sender EventArgs e) IntPtr a = new IntPtr(-1) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 32

Search Techniques Linear amp Binary

Searching is needed when we have a large array of some data or objects amp 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 amp finds the

position of elements Below you will find two search techniques viz Linear Search amp Binary

Search implemented in C The code is simple amp easy to understand amp can be modified as per

need

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 33

Code for Linear Search Technique in C Sharp

using System

using SystemText

using SystemThreadingTasks

namespace Linear_Search

class Program

static void Main(string[] args)

Int16[] array = new Int16[100]

Int16 search c number

ConsoleWriteLine(Enter the number of elements in arrayn)

number = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + numberToString() + numbersn)

for (c = 0 c lt number c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter the number to searchn)

search = ConvertToInt16(ConsoleReadLine())

for (c = 0 c lt number c++)

if (array[c] == search) if required element found

ConsoleWriteLine(searchToString() + is at locn + (c + 1)ToString() + n)

break

if (c == number)

ConsoleWriteLine(searchToString() + is not present in arrayn)

ConsoleReadLine()

httpwwwcode-kingsblogspotcom Page 34

Code for Binary Search Technique in C Sharp

namespace Binary_Search

class Program

static void Main(string[] args)

int c first last middle n search

Int16[] array = new Int16[100]

ConsoleWriteLine(Enter number of elementsn)

n = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + nToString() + integersn)

for (c = 0 c lt n c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter value to findn)

search = ConvertToInt16(ConsoleReadLine())

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

while (first lt= last)

if (array[middle] lt search)

first = middle + 1

else if (array[middle] == search)

ConsoleWriteLine(search + found at location + (middle + 1))

break

else

last = middle - 1

middle = (first + last) 2

if (first gt last)

ConsoleWriteLine(Not found + search + is not present in the list)

httpwwwcode-kingsblogspotcom Page 35

Working With Strings The 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 amp 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 txtLengthText = textBoxTextLengthToString() trkBar1Maximum = textBoxTextLength private void trackBar1_Scroll(object sender EventArgs e) Set the Max Value of second TrackBar trkBar2Maximum = textBoxTextLength - trkBar1Value textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString()

httpwwwcode-kingsblogspotcom Page 36

txtTotCharsText = trkBar2ValueToString() textBoxSelect()

Let us understand the working of this property with a simple String ABCDEFGH Suppose

you wanted to select the characters from between B amp C and Between F amp 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 ie

include A as well in the selection

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 ie a reduced

Maximum value

private void trackBar2_Scroll(object sender EventArgs e) textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString() txtTotCharsText = trkBar2ValueToString()

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 29: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 29

Then using host name get the IP address list IPHostEntry ipEntry = SystemNetDnsGetHostEntry(StringHost) IPAddress[] address = ipEntryAddressList for (int i = 0 i lt addressLength i++) ConsoleWriteLine() ConsoleWriteLine(IP Address Type 0 1 i address[i]ToString()) ConsoleRead()

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 30

Monitor Turn OnOffStandBy in C

You might want to change your display settings in a running program The code behind requires

the Import of a Dll amp execution of a function SendMessage() by supplying 4 parameters The

value of the fourth parameter having values 0 1 amp 2 has the monitor in the states ON STAND

BY amp 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 SystemWindowsForms using SystemRuntimeInteropServices namespace Turn_Off_Monitor public partial class Form1 Form public Form1() InitializeComponent() [DllImport(user32dll)] public static extern IntPtr SendMessage(IntPtr hWnd uint 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(thisHandle WM_SYSCOMMAND b a) private void btnMonitorOff_Click(object sender EventArgs e) IntPtr a = new IntPtr(2) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

httpwwwcode-kingsblogspotcom Page 31

private void btnMonitorOn_Click(object sender EventArgs e) IntPtr a = new IntPtr(-1) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 32

Search Techniques Linear amp Binary

Searching is needed when we have a large array of some data or objects amp 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 amp finds the

position of elements Below you will find two search techniques viz Linear Search amp Binary

Search implemented in C The code is simple amp easy to understand amp can be modified as per

need

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 33

Code for Linear Search Technique in C Sharp

using System

using SystemText

using SystemThreadingTasks

namespace Linear_Search

class Program

static void Main(string[] args)

Int16[] array = new Int16[100]

Int16 search c number

ConsoleWriteLine(Enter the number of elements in arrayn)

number = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + numberToString() + numbersn)

for (c = 0 c lt number c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter the number to searchn)

search = ConvertToInt16(ConsoleReadLine())

for (c = 0 c lt number c++)

if (array[c] == search) if required element found

ConsoleWriteLine(searchToString() + is at locn + (c + 1)ToString() + n)

break

if (c == number)

ConsoleWriteLine(searchToString() + is not present in arrayn)

ConsoleReadLine()

httpwwwcode-kingsblogspotcom Page 34

Code for Binary Search Technique in C Sharp

namespace Binary_Search

class Program

static void Main(string[] args)

int c first last middle n search

Int16[] array = new Int16[100]

ConsoleWriteLine(Enter number of elementsn)

n = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + nToString() + integersn)

for (c = 0 c lt n c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter value to findn)

search = ConvertToInt16(ConsoleReadLine())

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

while (first lt= last)

if (array[middle] lt search)

first = middle + 1

else if (array[middle] == search)

ConsoleWriteLine(search + found at location + (middle + 1))

break

else

last = middle - 1

middle = (first + last) 2

if (first gt last)

ConsoleWriteLine(Not found + search + is not present in the list)

httpwwwcode-kingsblogspotcom Page 35

Working With Strings The 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 amp 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 txtLengthText = textBoxTextLengthToString() trkBar1Maximum = textBoxTextLength private void trackBar1_Scroll(object sender EventArgs e) Set the Max Value of second TrackBar trkBar2Maximum = textBoxTextLength - trkBar1Value textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString()

httpwwwcode-kingsblogspotcom Page 36

txtTotCharsText = trkBar2ValueToString() textBoxSelect()

Let us understand the working of this property with a simple String ABCDEFGH Suppose

you wanted to select the characters from between B amp C and Between F amp 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 ie

include A as well in the selection

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 ie a reduced

Maximum value

private void trackBar2_Scroll(object sender EventArgs e) textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString() txtTotCharsText = trkBar2ValueToString()

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 30: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 30

Monitor Turn OnOffStandBy in C

You might want to change your display settings in a running program The code behind requires

the Import of a Dll amp execution of a function SendMessage() by supplying 4 parameters The

value of the fourth parameter having values 0 1 amp 2 has the monitor in the states ON STAND

BY amp 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 SystemWindowsForms using SystemRuntimeInteropServices namespace Turn_Off_Monitor public partial class Form1 Form public Form1() InitializeComponent() [DllImport(user32dll)] public static extern IntPtr SendMessage(IntPtr hWnd uint 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(thisHandle WM_SYSCOMMAND b a) private void btnMonitorOff_Click(object sender EventArgs e) IntPtr a = new IntPtr(2) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

httpwwwcode-kingsblogspotcom Page 31

private void btnMonitorOn_Click(object sender EventArgs e) IntPtr a = new IntPtr(-1) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 32

Search Techniques Linear amp Binary

Searching is needed when we have a large array of some data or objects amp 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 amp finds the

position of elements Below you will find two search techniques viz Linear Search amp Binary

Search implemented in C The code is simple amp easy to understand amp can be modified as per

need

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 33

Code for Linear Search Technique in C Sharp

using System

using SystemText

using SystemThreadingTasks

namespace Linear_Search

class Program

static void Main(string[] args)

Int16[] array = new Int16[100]

Int16 search c number

ConsoleWriteLine(Enter the number of elements in arrayn)

number = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + numberToString() + numbersn)

for (c = 0 c lt number c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter the number to searchn)

search = ConvertToInt16(ConsoleReadLine())

for (c = 0 c lt number c++)

if (array[c] == search) if required element found

ConsoleWriteLine(searchToString() + is at locn + (c + 1)ToString() + n)

break

if (c == number)

ConsoleWriteLine(searchToString() + is not present in arrayn)

ConsoleReadLine()

httpwwwcode-kingsblogspotcom Page 34

Code for Binary Search Technique in C Sharp

namespace Binary_Search

class Program

static void Main(string[] args)

int c first last middle n search

Int16[] array = new Int16[100]

ConsoleWriteLine(Enter number of elementsn)

n = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + nToString() + integersn)

for (c = 0 c lt n c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter value to findn)

search = ConvertToInt16(ConsoleReadLine())

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

while (first lt= last)

if (array[middle] lt search)

first = middle + 1

else if (array[middle] == search)

ConsoleWriteLine(search + found at location + (middle + 1))

break

else

last = middle - 1

middle = (first + last) 2

if (first gt last)

ConsoleWriteLine(Not found + search + is not present in the list)

httpwwwcode-kingsblogspotcom Page 35

Working With Strings The 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 amp 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 txtLengthText = textBoxTextLengthToString() trkBar1Maximum = textBoxTextLength private void trackBar1_Scroll(object sender EventArgs e) Set the Max Value of second TrackBar trkBar2Maximum = textBoxTextLength - trkBar1Value textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString()

httpwwwcode-kingsblogspotcom Page 36

txtTotCharsText = trkBar2ValueToString() textBoxSelect()

Let us understand the working of this property with a simple String ABCDEFGH Suppose

you wanted to select the characters from between B amp C and Between F amp 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 ie

include A as well in the selection

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 ie a reduced

Maximum value

private void trackBar2_Scroll(object sender EventArgs e) textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString() txtTotCharsText = trkBar2ValueToString()

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 31: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 31

private void btnMonitorOn_Click(object sender EventArgs e) IntPtr a = new IntPtr(-1) IntPtr b = new IntPtr(0xF170) const int WM_SYSCOMMAND = 0x0112 SendMessage(thisHandle WM_SYSCOMMAND b a)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 32

Search Techniques Linear amp Binary

Searching is needed when we have a large array of some data or objects amp 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 amp finds the

position of elements Below you will find two search techniques viz Linear Search amp Binary

Search implemented in C The code is simple amp easy to understand amp can be modified as per

need

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 33

Code for Linear Search Technique in C Sharp

using System

using SystemText

using SystemThreadingTasks

namespace Linear_Search

class Program

static void Main(string[] args)

Int16[] array = new Int16[100]

Int16 search c number

ConsoleWriteLine(Enter the number of elements in arrayn)

number = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + numberToString() + numbersn)

for (c = 0 c lt number c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter the number to searchn)

search = ConvertToInt16(ConsoleReadLine())

for (c = 0 c lt number c++)

if (array[c] == search) if required element found

ConsoleWriteLine(searchToString() + is at locn + (c + 1)ToString() + n)

break

if (c == number)

ConsoleWriteLine(searchToString() + is not present in arrayn)

ConsoleReadLine()

httpwwwcode-kingsblogspotcom Page 34

Code for Binary Search Technique in C Sharp

namespace Binary_Search

class Program

static void Main(string[] args)

int c first last middle n search

Int16[] array = new Int16[100]

ConsoleWriteLine(Enter number of elementsn)

n = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + nToString() + integersn)

for (c = 0 c lt n c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter value to findn)

search = ConvertToInt16(ConsoleReadLine())

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

while (first lt= last)

if (array[middle] lt search)

first = middle + 1

else if (array[middle] == search)

ConsoleWriteLine(search + found at location + (middle + 1))

break

else

last = middle - 1

middle = (first + last) 2

if (first gt last)

ConsoleWriteLine(Not found + search + is not present in the list)

httpwwwcode-kingsblogspotcom Page 35

Working With Strings The 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 amp 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 txtLengthText = textBoxTextLengthToString() trkBar1Maximum = textBoxTextLength private void trackBar1_Scroll(object sender EventArgs e) Set the Max Value of second TrackBar trkBar2Maximum = textBoxTextLength - trkBar1Value textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString()

httpwwwcode-kingsblogspotcom Page 36

txtTotCharsText = trkBar2ValueToString() textBoxSelect()

Let us understand the working of this property with a simple String ABCDEFGH Suppose

you wanted to select the characters from between B amp C and Between F amp 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 ie

include A as well in the selection

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 ie a reduced

Maximum value

private void trackBar2_Scroll(object sender EventArgs e) textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString() txtTotCharsText = trkBar2ValueToString()

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 32: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 32

Search Techniques Linear amp Binary

Searching is needed when we have a large array of some data or objects amp 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 amp finds the

position of elements Below you will find two search techniques viz Linear Search amp Binary

Search implemented in C The code is simple amp easy to understand amp can be modified as per

need

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 33

Code for Linear Search Technique in C Sharp

using System

using SystemText

using SystemThreadingTasks

namespace Linear_Search

class Program

static void Main(string[] args)

Int16[] array = new Int16[100]

Int16 search c number

ConsoleWriteLine(Enter the number of elements in arrayn)

number = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + numberToString() + numbersn)

for (c = 0 c lt number c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter the number to searchn)

search = ConvertToInt16(ConsoleReadLine())

for (c = 0 c lt number c++)

if (array[c] == search) if required element found

ConsoleWriteLine(searchToString() + is at locn + (c + 1)ToString() + n)

break

if (c == number)

ConsoleWriteLine(searchToString() + is not present in arrayn)

ConsoleReadLine()

httpwwwcode-kingsblogspotcom Page 34

Code for Binary Search Technique in C Sharp

namespace Binary_Search

class Program

static void Main(string[] args)

int c first last middle n search

Int16[] array = new Int16[100]

ConsoleWriteLine(Enter number of elementsn)

n = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + nToString() + integersn)

for (c = 0 c lt n c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter value to findn)

search = ConvertToInt16(ConsoleReadLine())

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

while (first lt= last)

if (array[middle] lt search)

first = middle + 1

else if (array[middle] == search)

ConsoleWriteLine(search + found at location + (middle + 1))

break

else

last = middle - 1

middle = (first + last) 2

if (first gt last)

ConsoleWriteLine(Not found + search + is not present in the list)

httpwwwcode-kingsblogspotcom Page 35

Working With Strings The 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 amp 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 txtLengthText = textBoxTextLengthToString() trkBar1Maximum = textBoxTextLength private void trackBar1_Scroll(object sender EventArgs e) Set the Max Value of second TrackBar trkBar2Maximum = textBoxTextLength - trkBar1Value textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString()

httpwwwcode-kingsblogspotcom Page 36

txtTotCharsText = trkBar2ValueToString() textBoxSelect()

Let us understand the working of this property with a simple String ABCDEFGH Suppose

you wanted to select the characters from between B amp C and Between F amp 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 ie

include A as well in the selection

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 ie a reduced

Maximum value

private void trackBar2_Scroll(object sender EventArgs e) textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString() txtTotCharsText = trkBar2ValueToString()

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 33: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 33

Code for Linear Search Technique in C Sharp

using System

using SystemText

using SystemThreadingTasks

namespace Linear_Search

class Program

static void Main(string[] args)

Int16[] array = new Int16[100]

Int16 search c number

ConsoleWriteLine(Enter the number of elements in arrayn)

number = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + numberToString() + numbersn)

for (c = 0 c lt number c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter the number to searchn)

search = ConvertToInt16(ConsoleReadLine())

for (c = 0 c lt number c++)

if (array[c] == search) if required element found

ConsoleWriteLine(searchToString() + is at locn + (c + 1)ToString() + n)

break

if (c == number)

ConsoleWriteLine(searchToString() + is not present in arrayn)

ConsoleReadLine()

httpwwwcode-kingsblogspotcom Page 34

Code for Binary Search Technique in C Sharp

namespace Binary_Search

class Program

static void Main(string[] args)

int c first last middle n search

Int16[] array = new Int16[100]

ConsoleWriteLine(Enter number of elementsn)

n = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + nToString() + integersn)

for (c = 0 c lt n c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter value to findn)

search = ConvertToInt16(ConsoleReadLine())

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

while (first lt= last)

if (array[middle] lt search)

first = middle + 1

else if (array[middle] == search)

ConsoleWriteLine(search + found at location + (middle + 1))

break

else

last = middle - 1

middle = (first + last) 2

if (first gt last)

ConsoleWriteLine(Not found + search + is not present in the list)

httpwwwcode-kingsblogspotcom Page 35

Working With Strings The 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 amp 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 txtLengthText = textBoxTextLengthToString() trkBar1Maximum = textBoxTextLength private void trackBar1_Scroll(object sender EventArgs e) Set the Max Value of second TrackBar trkBar2Maximum = textBoxTextLength - trkBar1Value textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString()

httpwwwcode-kingsblogspotcom Page 36

txtTotCharsText = trkBar2ValueToString() textBoxSelect()

Let us understand the working of this property with a simple String ABCDEFGH Suppose

you wanted to select the characters from between B amp C and Between F amp 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 ie

include A as well in the selection

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 ie a reduced

Maximum value

private void trackBar2_Scroll(object sender EventArgs e) textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString() txtTotCharsText = trkBar2ValueToString()

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 34: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 34

Code for Binary Search Technique in C Sharp

namespace Binary_Search

class Program

static void Main(string[] args)

int c first last middle n search

Int16[] array = new Int16[100]

ConsoleWriteLine(Enter number of elementsn)

n = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter + nToString() + integersn)

for (c = 0 c lt n c++)

array[c] = new Int16()

array[c] = ConvertToInt16(ConsoleReadLine())

ConsoleWriteLine(Enter value to findn)

search = ConvertToInt16(ConsoleReadLine())

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

while (first lt= last)

if (array[middle] lt search)

first = middle + 1

else if (array[middle] == search)

ConsoleWriteLine(search + found at location + (middle + 1))

break

else

last = middle - 1

middle = (first + last) 2

if (first gt last)

ConsoleWriteLine(Not found + search + is not present in the list)

httpwwwcode-kingsblogspotcom Page 35

Working With Strings The 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 amp 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 txtLengthText = textBoxTextLengthToString() trkBar1Maximum = textBoxTextLength private void trackBar1_Scroll(object sender EventArgs e) Set the Max Value of second TrackBar trkBar2Maximum = textBoxTextLength - trkBar1Value textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString()

httpwwwcode-kingsblogspotcom Page 36

txtTotCharsText = trkBar2ValueToString() textBoxSelect()

Let us understand the working of this property with a simple String ABCDEFGH Suppose

you wanted to select the characters from between B amp C and Between F amp 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 ie

include A as well in the selection

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 ie a reduced

Maximum value

private void trackBar2_Scroll(object sender EventArgs e) textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString() txtTotCharsText = trkBar2ValueToString()

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 35: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 35

Working With Strings The 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 amp 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 txtLengthText = textBoxTextLengthToString() trkBar1Maximum = textBoxTextLength private void trackBar1_Scroll(object sender EventArgs e) Set the Max Value of second TrackBar trkBar2Maximum = textBoxTextLength - trkBar1Value textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString()

httpwwwcode-kingsblogspotcom Page 36

txtTotCharsText = trkBar2ValueToString() textBoxSelect()

Let us understand the working of this property with a simple String ABCDEFGH Suppose

you wanted to select the characters from between B amp C and Between F amp 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 ie

include A as well in the selection

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 ie a reduced

Maximum value

private void trackBar2_Scroll(object sender EventArgs e) textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString() txtTotCharsText = trkBar2ValueToString()

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 36: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 36

txtTotCharsText = trkBar2ValueToString() textBoxSelect()

Let us understand the working of this property with a simple String ABCDEFGH Suppose

you wanted to select the characters from between B amp C and Between F amp 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 ie

include A as well in the selection

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 ie a reduced

Maximum value

private void trackBar2_Scroll(object sender EventArgs e) textBoxSelectionStart = trkBar1Value txtSelStartText = trkBar1ValueToString() textBoxSelectionLength = trkBar2Value txtSelEndText = (trkBar1Value + trkBar2Value)ToString() txtTotCharsText = trkBar2ValueToString()

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 37: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 37

textBoxSelect()

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 38: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 38

Matrix Multiplication in C

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

The code has a main class which consists of 3 functions

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

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 39: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 39

public void ReadMatrix() ConsoleWriteLine(nPlease Enter Details of First Matrix) ConsoleWrite(nNumber of Rows in First Matrix ) int m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in First Matrix ) int n = intParse(ConsoleReadLine()) a = new int[m n] ConsoleWriteLine(nEnter the elements of First Matrix ) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) try WriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) ConsoleWriteLine(nPlease Enter a Valid Value) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) a[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) ConsoleWriteLine(nPlease Enter Details of Second Matrix) ConsoleWrite(nNumber of Rows in Second Matrix ) m = intParse(ConsoleReadLine()) ConsoleWrite(nNumber of Columns in Second Matrix ) n = intParse(ConsoleReadLine()) b = new int[m n] ConsoleWriteLine(nPlease Enter Elements of Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) try ConsoleWriteLine(Enter Element + (1 + i)ToString() + + (1 + j)ToString()) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch try

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 40: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 40

ConsoleWriteLine(nPlease Enter a Valid Value) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) catch ConsoleWriteLine(nPlease Enter a Valid Value(Final Chance)) b[i j] = intParse(ConsoleReadLine()) ConsoleWriteLine( Value Accepted) public void PrintMatrix() ConsoleWriteLine(nFirst Matrix) for (int i = 0 i lt aGetLength(0) i++) for (int j = 0 j lt aGetLength(1) j++) ConsoleWrite(t + a[i j]) ConsoleWriteLine() ConsoleWriteLine(n Second Matrix) for (int i = 0 i lt bGetLength(0) i++) for (int j = 0 j lt bGetLength(1) j++) ConsoleWrite(t + b[i j]) ConsoleWriteLine() ConsoleWriteLine(n Resultant Matrix by Multiplying First amp Second Matrix) for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) ConsoleWrite(t + c[i j]) ConsoleWriteLine() ConsoleWriteLine(Do You Want To Multiply Once Again (YN)) if (ConsoleReadLine()ToString() == y || ConsoleReadLine()ToString() == Y || ConsoleReadKey()ToString() == y || ConsoleReadKey()ToString() == Y) MatrixMultiplication mm = new MatrixMultiplication() mmReadMatrix() mmMultiplyMatrix() mmPrintMatrix() else

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 41: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 41

ConsoleWriteLine(nMatrix Multiplicationn) ConsoleReadKey() EnvironmentExit(-1) public void MultiplyMatrix() if (aGetLength(1) == bGetLength(0)) c = new int[aGetLength(0) bGetLength(1)] for (int i = 0 i lt cGetLength(0) i++) for (int j = 0 j lt cGetLength(1) j++) c[i j] = 0 for (int k = 0 k lt aGetLength(1) k++) OR kltbGetLength(0) c[i j] = c[i j] + a[i k] b[k j] else ConsoleWriteLine(n Number of columns in First Matrix should be equal to Number of rows in Second Matrix) ConsoleWriteLine(n Please re-enter correct dimensions) EnvironmentExit(-1)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 42: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 42

DataGridView Filter amp Expressions C

Often we need to filter a DataGridView in our database programs The C datagrid is the best tool for

database display amp modification There is an easy shortcut to filtering a DataTable in C for the datagrid

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 amp Item Total This DataTable is then displayed in the C datagrid The fourth amp fifth columns

have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns) We add multiple rows

amp let the Tax amp Total get calculated automatically through the Expression value of the Column The

application of expressions is simple just type what you want For example if you want the 10 Tax

Column to generate values automatically you can set the ColumnExpression as ltColumn1gt =

ltColumn2gt ltColumn3gt 01 where the Columns are Tax Price amp Quantity respectively Note a hint

that the columns are specified as a decimal type

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 amp clicking the

corresponding buttons The Filter expressions are calculated by simply picking up the values from the

validating TextBoxes amp matching them to their Column name Note that the text changes dynamically on

the ButtonText property allowing 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()

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 43: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 43

DataTable dt = new DataTable() Form Table that Persists throughout private void Form1_Load(object sender EventArgs e) DataColumn Item_Name = new DataColumn(Item_Name Define TypeGetType(SystemString)) DataColumn Item_Price = new DataColumn(Item_Price the input TypeGetType(SystemDecimal)) DataColumn Item_Qty = new DataColumn(Item_Qty Columns TypeGetType(SystemDecimal)) DataColumn Item_Tax = new DataColumn(Item_tax Define Tax TypeGetType(SystemDecimal)) Item_Tax column is calculated (10 Tax) Item_TaxExpression = Item_Price Item_Qty 01 DataColumn Item_Total = new DataColumn(Item_Total Define Total TypeGetType(SystemDecimal)) Item_Total column is calculated as (Price Qty + Tax) Item_TotalExpression = Item_Price Item_Qty + Item_Tax dtColumnsAdd(Item_Name) Add 4 dtColumnsAdd(Item_Price) Columns dtColumnsAdd(Item_Qty) to dtColumnsAdd(Item_Tax) the dtColumnsAdd(Item_Total) Datatable private void btnInsert_Click(object sender EventArgs e) dtRowsAdd(txtItemNameText txtItemPriceText txtItemQtyText) MessageBoxShow(Row Inserted) private void btnShowFinalTable_Click(object sender EventArgs e) thisHeight = 637 Extend dgvDataSource = dt btnShowFinalTableEnabled = 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 = dtCopy() Copy existing data Apply Filter Value

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 44: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 44

NewDTDefaultViewRowFilter = Item_Price = + txtPriceFilterText + Set new table as DataSource dgvDataSource = NewDT private void txtPriceFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnPriceFilterText = Filter DataGridView by Price + txtPriceFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Qty = + txtQtyFilterText + dgvDataSource = NewDT private void txtQtyFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnQtyFilterText = Filter DataGridView by Total + txtQtyFilterText 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 = dtCopy() NewDTDefaultViewRowFilter = Item_Total = + txtTotalFilterText + dgvDataSource = NewDT private void txtTotalFilter_TextChanged(object sender EventArgs e) Change Button Text Dynamically btnTotalFilterText = Filter DataGridView by Total + txtTotalFilterText private void btnFilterReset_Click(object sender EventArgs e) DataTable NewDT = new DataTable() NewDT = dtCopy() dgvDataSource = NewDT

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 45: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 45

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 46: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 46

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 47: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 47

Stream Writer Basics

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 amp the second one specifies if you would like to replace or overwrite an existing

fileThe 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() InitializeComponent() private void btnChoosePath_Click(object sender EventArgs e) if (SFDShowDialog() == SystemWindowsFormsDialogResultOK) txtFilePathText = SFDFileName txtFilePathText += txt private void btnSaveFile_Click(object sender EventArgs e) SystemIOStreamWriter objFile = new SystemIOStreamWriter(txtFilePathTexttrue) for (int i = 0 i lt txtContentsLinesLength i++) objFileWriteLine(txtContentsLines[i]ToString()) objFileClose()

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 48: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 48

MessageBoxShow(Total Number of Lines Written + txtContentsLinesLengthToString()) private void Form1_Load(object sender EventArgs e) Anything

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 49: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 49

Send an Email through C

The Net Framework has a very good support for web applications The SystemNetMail can be

used to send Emails very easily All you require is a valid Username amp Password Attachments

of various file types 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 amp is checked to work well in all conditions

The MailMessage class contains everything youll need to set to send an email The information

like From To Subject CC etc 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(you

can download the code below to watch this)

public void SendEmail() try MailMessage mailObject = new MailMessage() SmtpClient SmtpServer = new SmtpClient(smtpgmailcom) mailObjectFrom = new MailAddress(txtFromText) mailObjectToAdd(txtToText) mailObjectSubject = txtSubjectText mailObjectBody = txtBodyText if (txtAttachText = ) Check if Attachment Exists SystemNetMailAttachment attachmentObject attachmentObject = new SystemNetMailAttachment(txtAttachText) mailObjectAttachmentsAdd(attachmentObject) SmtpServerPort = 587 SmtpServerCredentials = new SystemNetNetworkCredential(txtFromText txtPassKeyText) SmtpServerEnableSsl = true SmtpServerSend(mailObject) MessageBoxShow(Mail Sent Successfully) catch (Exception ex) MessageBoxShow(Some Error Plz Try Again httpwwwcode-kingsblogspotcom)

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 50: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 50

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 51: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 51

Use 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 fields Working with combo boxes

is much easier compared to text boxes We can easily bind fields 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

Set the Value Member property to the column that you want to choose the value from

Consider a table shown below

Item Number Item Name

1 TV

2 Fridge

3 Phone

4 Laptop

5 Speakers

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 52: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 52

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 amp display the columns in two combo boxesThe following

example shows a two-way dependency ie 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 changesThe 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 public Form1() InitializeComponent() private void Form1_Load(object sender EventArgs e) Create The Data Table DataTable dt = new DataTable() Set Columns dtColumnsAdd(Item Number) dtColumnsAdd(Item Name) Add RowsRecords dtRowsAdd(1 TV) dtRowsAdd(2Fridge) dtRowsAdd(3Phone) dtRowsAdd(4 Laptop) dtRowsAdd(5 Speakers) Set Data Source Property comboBox1DataSource = dt comboBox2DataSource = dt Set Combobox 1 Properties comboBox1ValueMember = Item Number comboBox1DisplayMember = Item Number Set Combobox 2 Properties comboBox2ValueMember = Item Number comboBox2DisplayMember = Item Name

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 53: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 53

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 54: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 54

Right Click Menu in C

Are you one of those looking for the Tool called Right Click Menu Well stop looking

Formally known as the Context Menu Strip in Net Framework it provides a convenient way to

create the Right Click menuStart off by choosing the tool named ContextMenuStrip in the

Toolbox window under the Menus amp Toolbars tab Works just like the Menu tool Add amp 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 forms Designercs 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 amp Y coordinates that we supply next(the second amp third

arguments) The best method is to place an invisible control at the location (00) in the form

Then the arguments to be passed are the eX amp eY in the Show() method In short

ContextMenuStripShow(UnusedControleXeY)

using SystemWindowsForms namespace WindowsFormsApplication1 public partial class Form1 Form public Form1() InitializeComponent() private void Form1_MouseClick(object sender MouseEventArgs e) if (eButton == SystemWindowsFormsMouseButtonsRight) contextMenuStrip1Show(button1eXeY) string str = httpwwwcode-kingsblogspotcom private void ToolMenu1_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the First Menu Item str) private void ToolMenu2_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Second Menu Item str)

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 55: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 55

private void ToolMenu3_Click(object sender EventArgs e) MessageBoxShow(You Have Clicked the Third Menu Item str)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 56: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 56

Save Custom User Settings amp Preferences

Your C application settings allow you to store and retrieve custom property settings and other

information for your application These properties amp settings can be manipulated at runtime

using ProjectNameSpaceSettingsDefaultPropertyName 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 amp 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

Select the name amp type of the setting that required

Set default values in the value column

Suppose the namespace of the project is ProjectNameSpace amp property is PropertyName

To modify the setting at runtime and subsequently save it

ProjectNameSpaceSettingsDefaultPropertyName = DesiredValue

ProjectNameSpacePropertiesSettingsDefaultSave()

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

on the page

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 57: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 57

Basics of Polymorphism Explained

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 amp 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 ie 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 amp 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 public virtual void Calculate(int x) ConsoleWriteLine(Square Or Cube Which One ) public class CalSquare PolyClass public override void Calculate(int x) ConsoleWriteLine(Square ) Calculate the Square of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x ) )) public class CalSqRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Square Root Is ) Calculate the Square Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathSqrt( x))))

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 58: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 58

public class CalCube PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Is ) Calculate the cube of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(x x x))) public class CalCubeRoot PolyClass public override void Calculate(int x) ConsoleWriteLine(Cube Square Is ) Calculate the Cube Root of a number ConsoleWriteLine(ConvertToString(ConvertToInt64(MathPow(x (03333333333333))))) 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) ConsoleWriteLine(Enter Integer) x = ConvertToInt32(ConsoleReadLine()) CalculateObjCalculate( x ) ConsoleWriteLine(Aurevoir ) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 59: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 59

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 60: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 60

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 amp efficiently with the help of properties

A property with Get() can be read amp a property with Set() can be written Using both Get()

amp 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 SystemCollectionsGeneric using SystemText 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 set p_id = value private string m_name = stringEmpty public string Name get return m_name set m_name = value private string m_Purpose = stringEmpty public string P_Name

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 61: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 61

get return m_Purpose set m_Purpose = value using System namespace CreateProperties class Program static void Main(string[] args) Properties object1 = new Properties() Set All Properties One by One object1ID = 1 object1Name = wwwcode-kingsblogspotcom object1P_Name = Teach C ConsoleWriteLine(ID + object1IDToString()) ConsoleWriteLine(nName + object1Name) ConsoleWriteLine(nPurpose + object1P_Name) ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 62: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 62

Also properties can be used without defining a a variable to work with in the beginning We

can simply use get amp set without using the return keyword ie without explicitly referring to

another previously declared variable These are Auto-Implement properties The get amp set

keywords are immediately written after declaration of the variable in brackets Thus the

property name amp variable name are the same

using System

using SystemCollectionsGeneric

using SystemText

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

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 63: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 63

Class Inheritance

Classes can inherit from other classes They can gain PublicProtected 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 amp implement Base and Derived Classes

First we create a BaseClass and define the Constructor SHoW amp a function to square a given

number Next we create a derived class and define once again the Constructor SHoW amp 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() ConsoleWriteLine(BaseClass Constructor Calledn) public void Function() ConsoleWriteLine(BaseClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = number number ConsoleWriteLine(Square is + number + n) public void SHoW() ConsoleWriteLine(Inside the BaseClassn)

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 64: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 64

class DerivedClass BaseClass public DerivedClass() ConsoleWriteLine(DerivedClass Constructor Calledn) public new void Function() ConsoleWriteLine(DerivedClass Function Calledn Enter A Single No) int number = new int() number = ConvertToInt32(ConsoleReadLine()) number = ConvertToInt32(number) ConvertToInt32(number) ConvertToInt32(number) ConsoleWriteLine(Cube is + number + n) public new void SHoW() ConsoleWriteLine(Inside the DerivedClassn)

class Program static void Main(string[] args) DerivedClass dr = new DerivedClass() drFunction() Call DerivedClass Function ((BaseClass)dr)Function() Call BaseClass Version drSHoW() Call DerivedClass SHoW ((BaseClass)dr)SHoW() Call BaseClass Version ConsoleReadKey()

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 65: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 65

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 66: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 66

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 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) label1Text = ConvertToString(rdNext(1 9)) label2Text = ConvertToString(rdNext(1 9)) label3Text = ConvertToString(rdNext(1 9))

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 67: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 67

if (label1Text == label2Text ampamp label1Text == label3Text) MessageBoxShow(U HAVE WON + $ + label1Text+00+ ) else MessageBoxShow(Better Luck Next Time)

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 68: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 68

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 69: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 69

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 ie Suggest Append or

SuggestAppend Any choice would do but my favourite is the SuggestAppend In SuggestAppend Partial

entries make intelligent guesses if the lsquoSo Farrsquo 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 AutoCompleteCustomSouceAdd() function with

the required This function can be used at runtime to add list items in the box

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) textBox2AutoCompleteMode = AutoCompleteModeSuggestAppend textBox2AutoCompleteSource = AutoCompleteSourceCustomSource textBox2AutoCompleteCustomSourceAdd(code-kingsblogspotcom) private void button1_Click(object sender EventArgs e) textBox2AutoCompleteCustomSourceAdd(textBox1TextToString()) textBox1Clear()

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 70: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 70

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 71: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 71

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 72: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 72

Insert amp 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 Database1mdf 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 40 does not need the removal of amp = signs The

String is generated perfectly ready to use This step only applies to Net Framework 10 amp 20

There are two things left to be done now One to insert amp then to Retrieve We create an SQL command

in the standard SQL Query format Therefore inserting is done by the SQL command

Insert Into ltTableNamegt (Col1 Col2) Values (Value for Col1 Value for Col2)

Execution of the CommandSQL 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 amp 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

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 73: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 73

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 ltTableNamegt

To retreive specific columns use

Select Column1 Column2 From ltTableNamegt

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 4 When working with SQL Databases use the SystemDataSqlClient 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

ApplicationStartupPathToString() 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 amp would prove flawless to the integrity of the Database

using System using SystemDataSqlClient namespace Insert_Show public partial class Form1 Form public Form1() InitializeComponent() SqlConnection con = new SqlConnection(Data Source=SQLEXPRESSAttachDbFilename=+ ApplicationStartupPathToString() + Database1mdf) private void Form1_Load(object sender EventArgs e) MessageBoxShow(Click on Insert Button amp then on Show)

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 74: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 74

private void btnInsert_Click(object sender EventArgs e) SqlCommand cmd = new SqlCommand(INSERT INTO Table1 (fld1 fld2 fld3) VALUES ( I + + LOVE + + code-kingsblogspotcom + ) con) conOpen() cmdExecuteNonQuery() conClose() private void btnShow_Click(object sender EventArgs e) DataTable table = new DataTable() SqlDataAdapter adp = new SqlDataAdapter(Select from Table1 con) conOpen() adpFill(table) MessageBoxShow(tableRows[0][0] + + tableRows[0][1] + + tableRows[0][2])

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 75: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 75

Fetch Data from a Specified Position

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 amp 2

using System using SystemDataSqlClient namespace Data_Fetch_In_TableNet public partial class Form1 Form public Form1() InitializeComponent()

SqlConnection con = new SqlConnection(Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + ldquoDatabase1mdf Integrated Security=True User Instance=True) SqlDataAdapter adapter = new SqlDataAdapter() SqlCommand cmd = new SqlCommand()

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 76: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 76

DataTable dt = new DataTable() private void Form1_Load(object sender EventArgs e) SqlDataAdapter adapter = new SqlDataAdapter(select from Table1con) adapterSelectCommandConnectionConnectionString = Data Source=SQLEXPRESS AttachDbFilename=rdquo + ApplicationStartupPathToString() + Database1mdfIntegrated Security=True User Instance=True) conOpen() adapterFill(dt) conClose() private void button1_Click(object sender EventArgs e) Int16 x = ConvertToInt16(textBox1Text) Int16 y = ConvertToInt16(textBox2Text) string current =dtRows[x][y]ToString() MessageBoxShow(current)

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 77: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 77

Drawing with Mouse in C

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 and using

the function ColorFromArgb() The Random object gives us a random integer value to feed the

Red Blue amp Green values of Color(Which are between 0 and 255 for a 32 bit color interface)

The argument e gives us the source for identifying the button pressed which in this case is

desired to be MouseButtonsRight

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 78: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 78

using System namespace Mouse_Paint public partial class MainForm Form public MainForm() InitializeComponent() private Graphics m_objGraphics Random rd = new Random() private void MainForm_Load(object sender EventArgs e) m_objGraphics = thisCreateGraphics() private void MainForm_Close(object sender EventArgs e) m_objGraphicsDispose() private void MainForm_Click(object sender MouseEventArgs e) if (eButton == MouseButtonsRight)

m_objGraphicsClear(ColorFromArgb(rdNext(0255)rdNext(0255)rdNext(025

5))) private void MainForm_MouseMove(object sender MouseEventArgs e) Rectangle rectEllipse = new Rectangle() if (eButton = MouseButtonsLeft) return rectEllipseX = eX - 1 rectEllipseY = eY - 1 rectEllipseWidth = 5 rectEllipseHeight = 5 m_objGraphicsDrawEllipse(SystemDrawingPensBlue rectEllipse)

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 79: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 79

Please Note

Do not Copy amp Paste code written here instead type it in your Development Environment

To Comment or ask a question Click Here

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading

Page 80: 32 .Net C# CSharp Programs Version 4.0

httpwwwcode-kingsblogspotcom Page 80

Thank You For Reading